Okay, so I need to put many different lists into one list using Java. Here is the important code.
String jsonText = buffer.toString(); // gets what the URL returns as JSON
JSONObject obj = new JSONObject(jsonText); // using JSONObject to pass to a JSONArray to search for the JSON
List<List<String>> allInfo = new ArrayList();// list to put all the returned information
List<String> innerList = new ArrayList();
JSONArray linemanques = obj.getJSONArray("linemanques"); //selects the array to read from
for (int i = 0; i < linemanques.length(); i++) {
JSONObject questionParts = linemanques.getJSONObject(i);
quesnum = questionParts.getString("quesnum"); // all of questionParts.getString() are for getting the data in the JSONArray
questype = questionParts.getString("questype");
question = questionParts.getString("question");
ans1 = questionParts.getString("ans1");
ans2 = questionParts.getString("ans2");
ans3 = questionParts.getString("ans3");
ans4 = questionParts.getString("ans4");
correctans = questionParts.getString("correctans");
category = questionParts.getString("category");
notes = questionParts.getString("notes");
flag = questionParts.getString("flag");
innerList.add(quesnum);
innerList.add(questype);
innerList.add(question);
innerList.add(ans1);
innerList.add(ans2);
innerList.add(ans4);
innerList.add(correctans);
innerList.add(category);
innerList.add(notes);
innerList.add(flag);
allInfo.add(innerList);
}
return allInfo;
As shown above, I take a List called innerList and put it into another List, which is of type List called allInfo. In the for loop, I take the length of the JSONArray I'm using, and add the elements to innerList. Then, I take innerList and add it into allInfo, then return that.
By the way, here is the JSON.
{
"error": false,
"message": "Request successfully completed",
"linemanques": [
{
"quesnum": 1,
"questype": 1,
"question": "This is question #1",
"ans1": "This is answer 1",
"ans2": "This is answer 2\r\n",
"ans3": "This is answer 3\r\n\r\n\r\n",
"ans4": "This is answer 4",
"correctans": "ans4",
"notes": "This is a note",
"category": "2",
"flag": "ans4"
},
{
"quesnum": 2,
"questype": 2,
"question": "This is question #2",
"ans1": "This is Q2 ans 1",
"ans2": "This is Q2 ans2",
"ans3": "This is Q2 ans3",
"ans4": "This is Q2 ans4",
"correctans": "ans2",
"notes": "This is Q2 note 1",
"category": "5",
"flag": "ans2"
},
{
"quesnum": 3,
"questype": 6,
"question": "gkjhgjkgkg",
"ans1": "ghdfhdghfd",
"ans2": "Tuituiyt",
"ans3": "Tiuytui9",
"ans4": "Tauitui.247",
"correctans": "ans2",
"notes": "Article iutuC",
"category": "5",
"flag": "ans2"
},
{
"quesnum": 7,
"questype": 2,
"question": " how many",
"ans1": "isi",
"ans2": "thiis\\r\\n",
"ans3": "yes",
"ans4": "no",
"correctans": "yes",
"notes": "refer back to yes",
"category": "0",
"flag": "yes"
},
{
"quesnum": 8,
"questype": 2,
"question": " how many",
"ans1": "isi",
"ans2": "thiis",
"ans3": "yes",
"ans4": "no",
"correctans": "yes",
"notes": "refer back to yes",
"category": "0",
"flag": "yes"
},
{
"quesnum": 9,
"questype": 2,
"question": "How many apples can I eat in one day?",
"ans1": "42 apples",
"ans2": "6 apples",
"ans3": "89 apples",
"ans4": " 42 oranges",
"correctans": "ans2",
"notes": "try eating apples",
"category": "8",
"flag": "ans2"
},
{
"quesnum": 10,
"questype": 2,
"question": " how many",
"ans1": "isi",
"ans2": "thiis\\r\\n\\r\\n\\r\\n",
"ans3": "yes",
"ans4": "no",
"correctans": "yes",
"notes": "refer back to yes",
"category": "0",
"flag": "yes"
}
]
}
And this is the structure of the array I'm hoping for:
allInfo {
innerList {
JSONObject
JSONObject
JSONObject
}
innerList {
JSONObject
JSONObject
JSONObject
}
innerList {
JSONObject
JSONObject
JSONObject
}
innerList {
JSONObject
JSONObject
JSONObject
}
innerList {
JSONObject
JSONObject
JSONObject
}
innerList {
JSONObject
JSONObject
JSONObject
}
}
But instead, this is what I'm ending up with (i think):
allInfo {
innerList {
JSONObject
JSONObject
JSONObject
JSONObject
JSONObject
JSONObject
JSONObject
JSONObject
JSONObject
JSONObject
JSONObject
JSONObject
JSONObject
JSONObject
JSONObject
JSONObject
JSONObject
JSONObject
}
}
It's supposed to make multiple lists in one list so that I can call access to it and set text in a TextView like this:
textView.setText(allInfo.get(2).get(4)); //example
I guess if you place the line List<String> innerList = new ArrayList(); within the for loop, it will properly initialize the innerList each time.
I think you do it in a hard way.
you could use a library to deserializes your JSON like Jackson
So you could build pojo class out your keys
import com.fasterxml.jackson.databind.ObjectMapper;
class Pojo {
String quesnum;
int questype;
String question;
String ans1;
String ans2;
String ans3;
String no;
String correctans;
String notes;
int category;
String flag;
}
then use Jackson to do the job for you by calling
List<Pojo> allInfo = mapper.readValue(json, new TypeReference<List<Pojo>>() {});
If i understood correctly, you forget to clean innerList within for loop. You need to do:
innerList.clear()
Related
If I have a JSON like this:
{
"name": "Johnny",
"Gender": {
"male": true,
"female": false
},
"What does Johnny likes?": ["Travels", "Woman"],
"Travels": [
{
"Country": "Spain",
"City": "Madrid"
},
{
"Country": "Greece",
"City": "Kalokairi"
}
]
}
I know that I can do this to access to name:
object.getString("name");
To access gender I can do this:
JSONObject gender = (JSONObject) object.get("Gender");
gender.get("male");
gender.get("female");
To access What does Johnny likes? I can:
JSONArray likes = (JSONArray) objet.get("What does Johnny likes?");
Iterator<String> iterator = likes.iterator();
while (iterator.hasNext()) {
//code here
}
But how do I access Travels? I'm really not sure to understand it?
did you, try this?
JSONArray travels = (JSONArray) objet.get("Travels");
for(int j=0;j<travels.length();j++){
JSONObject travel = travels.getJSONObject(j);
}
I am fetching details from a database table which contains 3 rows in JAVA.
I am using JSONarray and JSONObject as follows
JSONObject jsonObject = new JSONObject();
JSONObject mainjsonObject = new JSONObject();
JSONArray ja=new JSONArray();
The data from table is put to the jsonObject as follows for each one:
String qry="select * from details";
ResultSet res = select .executeQuery(qry);
while(res.next){
String Name=res.getString("name");
.
.
jsonObject.put("Name", Name);
.
.
ja.put(jsonObject);
}
mainjsonObject.put("PERSONAL DETAILS",ja);
i should get the output json as follows:
{
"PERSONAL DETAILS": [
{
" name": "abc",
"age": "4",
"gender": "F",
"Place": "abc1"
},
{
" name": "xyz",
"age": "3",
"gender": "M",
"Place": "abc2"
}
]
}
But am getting same values in both like below:
{
"PERSONAL DETAILS": [
{
" name": "abc",
"age": "4",
"gender": "F",
"Place": "abc1"
},
{
" name": "abc",
"age": "4",
"gender": "F",
"Place": "abc1"
}
]
}
Please help me with a solution. I need to get all the values from the tables as an array in JSON format
you need to create new JSONObject in your loop otherwise the last record will be shown everywhere
while(res.next()){
String Name=res.getString("name");
jsonObject = new JSONObject();
// ^^^^^^^^
jsonObject.put("Name", res.getString(1));
jsonObject.put("age", res.getString(2));
jsonObject.put("gender", res.getString(3));
jsonObject.put("Place", res.getString(4));
ja.put(jsonObject);
}
The problem is that you are reusing the same JSONObject over and over. And this is basically a Map.
What you need to do is create a new JSONObject instance and put it in the array for each iteration:
JSONObject obj;
while (rs.next()) {
obj = new JSONObject();
// fill in obj
ja.put(obj);
}
i have data
like this:
{
"status": "success",
"message": "Student Statement Report",
"data": {
"data": [{
"id": "45",
"transaction_no": "45",
"transaction_date": "2017-05-25",
"transaction_type": "invoice",
"transaction_amount": "1010.00",
"related_invoice_id": "45",
"balance_amount": "1010.00",
"related_user_id": "436",
"related_user_group": "student",
"description": "",
"created_by": "Principal",
"updated_by": "Principal",
"created_at": "2017-05-25 11:57:39",
"updated_at": "2017-05-25 11:57:39"
}],
"opening_balance": 0,
"dates": ["2017-05-22 00:00:00", "2017-05-28 23:59:59"]
}
}
JSONObject jsonObject = new JSONObject(response);
and i am geeting Json expection error from here
String openingBalance = jsonObject.getString("opening_balance");
"opening_balance": 0,
so, my biggest question is should that zero (value) should be quoted or not?
You have to parse it like this:
JSONObject jsonObject = new JSONObject(response);
JSONObject data = jsonObject.getJSONObject("data");//Get Data object
int openingBalance = data.getInt("opening_balance");//Get opening balance
If you read the number as an Integer then quotation is not necessary. But if your read it as a String then you have to put quotation.
To read as an Integer you can use getInt("json_key")
& for String getString("json_key").
JSONObject jsonObject = new JSONObject(response);
JSONObject data = jsonObject.getJSONObject("data");//Get Data object
int openingBalance = data.getInt("opening_balance");//Get opening balance
I have two json files. I need to parse and join the json into a single structure
lineage.json
{
"lineage": [{
"sourceColumnId": "VMB_BESTADDRESS.SNAPSHOT_TS",
"description": "",
"targetColumnId": "VMB_BESTADDRESSUSAGE.NXREINS"
},
{
"sourceColumnId": "DSL_RECORD_SOURCES.MAMACT",
"description": "",
"targetColumnId": "G2_ZUMADF00.MAMACT"
},
{
"sourceColumnId": "DSL_RECORD_SOURCES.MAMADE",
"description": "",
"targetColumnId": "G2_ZUMADF00.HDF_S_POL_GEN"
}]
}
column.json
{
"column": [{
"ID": 39700,
"columnId": "VMB_BESTADDRESS.SNAPSHOT_TS",
"column": "SNAPSHOT_TS",
"dataType": "String",
"length": "",
"table": "VMB_BESTADDRESS",
},
{
"ID": 39701,
"columnId": "VMB_BESTADDRESSUSAGE.NXREINS",
"column": "NXREINS",
"dataType": "String",
"length": "",
"table": "VMB_BESTADDRESSUSAGE",
},
{
"ID": 39702,
"columnId": "VMB_BESTADDRESSUSAGE.PKADDRESSCODE",
"column": "PKADDRESSCODE",
"dataType": "String",
"length": "",
"table": "VMB_BESTADDRESSUSAGE",
}]
}
I need to join the two jsons such that for every match of sourcecolumnId and targetcolumnid in column the following json structure must be populated
{
output:{
sourceColumnId:VMB_BESTADDRESS.SNAPSHOT_TS,
sourceColumnName:SNAPSHOT_TS,
targetColumnId:VMB_BESTADDRESSUSAGE.NXREINS,
targetColumnNameNXREINS,
}
}
I need to join lookup two json to get the output such that
sourceColumnName -> column name from column.json whose columnId and sourceColumnId are same.
similarly for targetcolumnName also.
String str = "xxx"; // column.json
JSONArray jsonArrayColumn = JSON.parseObject(str);
Map<String, JSONObject> column = new HashMap(); // {id:name}
for(int i = 0; i < jsonArrayColumn.size(); i++){ // loop
JSONObject obj = jsonArrayColumn.getJSONObject(i);
column.put(obj.getString("columnId"), obj.getString("column"));
}
String str2 = "xxx"; // lineage.json
JSONArray jsonArrayLineage = JSON.parseObject(str2);
JSONArray resultArray = new JSONArray();
for(int i = 0; i < jsonArrayLineage.size(); i++){ // loop
JSONObject lineageObj = jsonArrayLineage.getJSONObject(i);
JSONObject obj = new JSONObject();
obj.put("sourceColumnId", lineageObj.get("sourceColumnId"));
obj.put("sourceColumnName", column.get(lineageObj.get("sourceColumnId")));
obj.put("targetColumnId", lineageObj.get("targetColumnId"));
obj.put("targetColumnName", column.get(lineageObj.get("targetColumnId")));
}
The resultArray is what you want.
I am using gson-2.5 for this. There is a slight difference in the format of these two jsons, where in the first one;
"usethis": [
{
"id": 111,
"text": "some text that i would like",
},
{
"id": 222,
"text": "someothertextiwouldlike",
}
]
I would have parsed this to get "text" this way, and everything would be ok;
JsonParser jp = new JsonParser();
JsonElement root = jp.parse(listcontents);
JsonObject rootobj = root.getAsJsonObject();
JsonArray items = rootobj.get("usethis").getAsJsonArray();
for(int i = 0; i < items.size(); i++) {
JsonObject item = items.get(i).getAsJsonObject();
String thetext = item.get("text").getAsString();
System.out.println("text: " + thetext + "\n");
}
The difference is that in the second one, I have nothing to get as the rootobject unlike in the first where I used "usethis";
[
{
"id": 111,
"text": "some text that i would like",
},
{
"id": 222,
"text": "someothertextiwouldlike",
}
]
And setting
rootobj.get("usethis").getAsJsonArray();
to
rootobj.get("").getAsJsonArray();
just gives me an error. How would I be able to parse the second json?
JsonElement is just a superclass of JsonArray and JsonObject.
JsonArray items = root.getAsJsonArray();
should do what you want.