I have array look like this :
"results":[
{
"code":"jne",
"name":"Jalur Nugraha Ekakurir (JNE)",
"costs":[
{
"service":"OKE",
"description":"Ongkos Kirim Ekonomis",
"cost":[
{
"value":38000,
"etd":"4-5",
"note":""
}
]
},
{
"service":"REG",
"description":"Layanan Reguler",
"cost":[
{
"value":44000,
"etd":"2-3",
"note":""
}
]
},
{
"service":"SPS",
"description":"Super Speed",
"cost":[
{
"value":349000,
"etd":"",
"note":""
}
]
},
{
"service":"YES",
"description":"Yakin Esok Sampai",
"cost":[
{
"value":98000,
"etd":"1-1",
"note":""
}
]
}
]
}
]
My code on android to process array, problem in my code on function "for" before I copy and edit another code from file :
JSONObject jsonObjsko = new JSONObject(rajaongkir);
String resultse = jsonObjsko.getString("results");
JSONArray jsonObjssto = new JSONArray(resultse);
JSONObject mJsonObject = jsonObjssto.getJSONObject(0);
costs = mJsonObject.getString("costs");
JSONArray jsonArray = new JSONArray(costs);
for (int k = 0; k < jsonArray.length(); k++) {
try {
JSONArray jsonArrayp = new JSONArray(costs);
JSONObject jsonObject = jsonArrayp.getJSONObject(k);
String serviceq = jsonObject.getString("cost");
String servicel = jsonObject.getString("service");
kon = String.valueOf(jsonArray.length());
kin = kin + k;
JSONArray jsonObjsstorng = new JSONArray(serviceq);
JSONObject mJsonObjectrng = jsonObjsstorng.getJSONObject(k);
String values = mJsonObjectrng.getString("value");
ShipPerActiv wp = new ShipPerActiv(servicel, values);
arraylist.add(wp);
}
catch (JSONException e) {
e.printStackTrace();
}
}
This code for ShipPerActiv for add arraylist :
public class ShipPerActiv {
private String services;
private String hongkir;
public ShipPerActiv(String services,String hongkir) {
this.services = services;
this.hongkir = hongkir;
}
public String getservices() {return this.services; }
public String gethongkir() {return this.hongkir; }
}
I tried use harddebug with kon & kin true function for normal but not on my listview just one int(0) not int(1)~etc
At first convert your StringObject to JSONObject and dont forget to add { at first of string and } to end of string:
JSONObject parentObject = new JSONObject("{"+"JsonString"+"}");
Then parse your object like this :
try {
JSONObject parentObject = new JSONObject(a);
JSONArray results = parentObject.getJSONArray("results");
JSONObject resultsObject=results.getJSONObject(0);
JSONArray costsArray = resultsObject.getJSONArray("costs");
for (int i = 0; i < costsArray.length(); i++) {
Log.d("CostsJsonObject" , costsArray.getJSONObject(i).toString());
}
} catch (JSONException e) {
Log.d("CostsJsonObject Exception" , e.toString());
}
And result :
I think your problem is on this code :
JSONObject mJsonObjectrng = jsonObjsstorng.getJSONObject(k);
Simply change it to :
JSONObject mJsonObjectrng = jsonObjsstorng.getJSONObject(0);
Hope it'll help you ;)
Related
Hi i was trying to parse a json array inside another json array. Help me with this.
my Json Array is
"results":[
{
"percentcompleted":0,
"requirers":[
{
"activityContext":null,
"auditReason":null,
"assignee":{
"sourceType":"InternalPerson",
"activitySourceType":{
"listId":"sysli000000000003037",
"sourceType":0,
"key":"0",
"displayName":"Person"
},
"locale":{
"id":"local000000000000001",
"displayName":"English"
},
"id":"emplo000000006156648",
"displayName":"Venkat Rao"
},
"targetDate":null,
"assignment":{
"id":"stcur000000000003182",
"displayName":null
},
"learningEvent":{
"id":"curra000000000003001",
"displayName":"Studieplan_test för OKQ8"
},
"jobTypeId":null,
"listIds":null,
"assignedOn":1502084325000,
"source":{
"sourceType":"InternalPerson",
"activitySourceType":{
"listId":"sysli000000000003037",
"sourceType":0,
"key":"0",
"displayName":"Person"
},
"locale":{
"id":"local000000000000001",
"displayName":"English"
},
"id":"emplo000000006156648",
"displayName":"Venkat Rao"
},
"required":true,
"actions":null,
"id":"currh000000000014343"
}
],
"basicdetail":{
"revokedOn":null,
"need_recert":false,
"curriculum":{
"id":"curra000000000003001",
"displayName":"Studieplan_test för OKQ8"
},
"recert_window_starts_on":null,
"createdBy":"vrao",
"updatedBy":"vrao",
"createdOn":1502084325000,
"updatedOn":1508357353000,
"status":{
"intStatus":400,
"description":"Assigned",
"displayName":"Assigned"
},
"type":"CURRICULUM",
"path":{
"id":"track000000000003081",
"displayName":"Studieplan"
},
"acquiredOn":null,
"assignee":{
"sourceType":"InternalPerson",
"activitySourceType":{
"listId":"sysli000000000003037",
"sourceType":0,
"key":"0",
"displayName":"Person"
},
"locale":{
"id":"local000000000000001",
"displayName":"English"
},
"id":"emplo000000006156648",
"displayName":"Venkat Rao"
},
"targetDate":null,
"startedOn":null,
"assignedOnDate":1502084325000,
"heldCertNo":"00003787",
"owner":{
"sourceType":"InternalPerson",
"activitySourceType":{
"listId":"sysli000000000003037",
"sourceType":0,
"key":"0",
"displayName":"Person"
},
"locale":{
"id":"local000000000000001",
"displayName":"English"
},
"id":"emplo000000006156648",
"displayName":"Venkat Rao"
},
"id":"stcur000000000003182",
"assigneeAdditionalDetails":{
"person_no":"VRAO",
"username":"VRAO"
}
},
"isgranted":null
},
and my Code to parse the above data is
public class CurriculaParser {
public ArrayList<CurriculaData> getData(String response)
{
ArrayList<CurriculaData> dataList = new ArrayList<>();
try {
JSONObject mainObj = new JSONObject(response);
JSONArray array = mainObj.getJSONArray("results");
CurriculaData data;
for(int i = 0;i<array.length();i++)
{
data = new CurriculaData();
JSONObject resObj = array.getJSONObject(i);
JSONArray reqArray = resObj.getJSONArray("requires");
for( int j =0;j<reqArray.length();j++) {
JSONObject reqObj = reqArray.getJSONObject(j);
JSONObject innerObj = reqObj.getJSONObject("learningEvent");
data.setTitle(innerObj.getString("displayName"));
data.setAssignedOn(reqObj.getString("assignedOn"));
}
JSONArray basicDetailArray = resObj.getJSONArray("basicdetail");
for(int k=0;k<basicDetailArray.length();k++) {
JSONObject basicDetailObj = basicDetailArray.getJSONObject(k);
JSONObject statusObj = basicDetailObj.getJSONObject("status");
data.setStatus(statusObj.getString("displayName"));
data.setAcquiredOn(basicDetailObj.getString("acquiredOn"));
JSONObject assignObj = basicDetailObj.getJSONObject("assignee");
data.setAssignedBy(assignObj.getString("displayName"));
}
dataList.add(data);
}
} catch (Exception e) {
e.printStackTrace();
}
return dataList;
}
and finally i got error like
org.json.JSONException: No value for requires
let me know the error what i made and iam a beginner in dealing with jsonarray inside another jsonarray
org.json.JSONException: No value for requires
JSONException
KEY mismatches on lookups
You should pass requirers instead of requires.
JSONArray reqArray = resObj.getJSONArray("requirers");
fixed the requires TYPO error
public class CurriculaParser {
public ArrayList<CurriculaData> getData(String response)
{
ArrayList<CurriculaData> dataList = new ArrayList<>();
try {
JSONObject mainObj = new JSONObject(response);
JSONArray array = mainObj.getJSONArray("results");
CurriculaData data;
for(int i = 0;i<array.length();i++)
{
data = new CurriculaData();
JSONObject resObj = array.getJSONObject(i);
JSONArray reqArray = resObj.getJSONArray("requirers");
for( int j =0;j<reqArray.length();j++) {
JSONObject reqObj = reqArray.getJSONObject(j);
JSONObject innerObj = reqObj.getJSONObject("learningEvent");
data.setTitle(innerObj.getString("displayName"));
data.setAssignedOn(reqObj.getString("assignedOn"));
}
JSONArray basicDetailArray = resObj.getJSONArray("basicdetail");
for(int k=0;k<basicDetailArray.length();k++) {
JSONObject basicDetailObj = basicDetailArray.getJSONObject(k);
JSONObject statusObj = basicDetailObj.getJSONObject("status");
data.setStatus(statusObj.getString("displayName"));
data.setAcquiredOn(basicDetailObj.getString("acquiredOn"));
JSONObject assignObj = basicDetailObj.getJSONObject("assignee");
data.setAssignedBy(assignObj.getString("displayName"));
}
dataList.add(data);
}
} catch (Exception e) {
e.printStackTrace();
}
I would need help to parse this JSONArray in my Android app. I'm a bit confused with JSONObjects and JSONArrays :
[
{
"nid": [
{
"value": "3"
}
],
"uid": [
{
"target_id": "1",
"url": "/user/1"
}
],
"field_image": [
{
"target_id": "2",
"alt": "alternate 1",
"title": "",
"width": "640",
"height": "640",
"url": "http://url"
},
{
"target_id": "3",
"alt": "alternate 2",
"title": "",
"width": "640",
"height": "640",
"url": "http://url"
}
]
}]
Here is what I've got to start the iteration :
public void onResponse(JSONArray response) {
try {
jsonResponse = "";
for (int i = 0; i < response.length(); i++) {
...
Here is your code to parse data,
private void parseData(){
try {
JSONArray jsonArray=new JSONArray(response);
JSONObject jsonObject=jsonArray.getJSONObject(0);
JSONArray jsonArrayNid=jsonObject.getJSONArray("nid");
JSONArray jsonArrayUid=jsonObject.getJSONArray("uid");
JSONArray jsonArrayField_image=jsonObject.getJSONArray("field_image");
for(int i=0;i<jsonArrayNid.length();i++){
JSONObject jsonObjectNid=jsonArrayNid.getJSONObject(i);
String value=jsonObjectNid.getString("value"); //here you get your nid value
}
for(int i=0;i<jsonArrayUid.length();i++){
JSONObject jsonObjectUid=jsonArrayUid.getJSONObject(i);
String target_id=jsonObjectUid.getString("target_id"); //here you get your uid target_id value
String url=jsonObjectUid.getString("url"); //here you get your uid url value
}
for(int i=0;i<jsonArrayField_image.length();i++){
JSONObject jsonObjectFieldImage=jsonArrayField_image.getJSONObject(i);
String target_id=jsonObjectFieldImage.getString("target_id");
String alt=jsonObjectFieldImage.getString("alt");
String title=jsonObjectFieldImage.getString("title");
String width=jsonObjectFieldImage.getString("width");
String height=jsonObjectFieldImage.getString("height");
String url=jsonObjectFieldImage.getString("url");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
for (int i = 0; i < response.length(); i++) {
JSONObject tobject = response.getJSONObject(i);
JSONArray nid = tobject.getJSONArray("nid");
JSONArray uid= tobject.getJSONArray("uid");
JSONArray field_image= tobject.getJSONArray("field_image");
//similarly you can loop inner jsonarrays
}
Use code according to you:
JSONArray array = null;
try {
array = new JSONArray(url); // your web url
JSONObject object = array.getJSONObject(0);
JSONArray array1 = object.getJSONArray("nid");
JSONObject object1 = array1.getJSONObject(0);
String value = object1.getString("value");
JSONArray array2 = object.getJSONArray("uid");
JSONObject object2 = array2.getJSONObject(0);
String target = object2.getString("target_id");
String url = object2.getString("url");
JSONArray array3 = object.getJSONArray("field_image");
JSONObject object3 = array3.getJSONObject(0);
String alt = object3.getString("alt");
Toast.makeText(Testing.this,value+"\n"+target+"\n"+url+"\n"+alt,Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
Try to parse like this.
In this code, jsonArray is the parent array which you have in your JSON.
for(int i=0;i<jsonArray.length();i++)
{
try {
JSONObject object=jsonArray.getJSONObject(i);
JSONArray imageArray=object.getJSONArray("field_image");
for(int j=0;j<imageArray.length();j++)
{
JSONObject imageObject=imageArray.getJSONObject(j);
String targetId=imageObject.getString("target_id");
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
Now :) if you have to parse something first look for some library:
http://www.java2s.com/Code/Jar/g/Downloadgson222jar.htm
Download gson.jar and then create java classes that mimic your desired json:
class C1{
private String value;
}
class C2{
private String target_id;
private String url;
}
class C3{
private String target_id;
private String alt;
private String title;
private String width;
private String height;
private String url;
}
class c4{
private List<C1> nid;
private List<C2> uid;
private List<C3> field_image;
}
Since you receive array from C4, you parse it like this:
public void onResponse(JSONArray response){
String value = response.toString();
GsonBuilder gb = new GsonBuilder();
Type arrayType = new TypeToken<List<C4>>() {}.getType();
List<C4> data = gb.create().fromJson(value, arrayType);
}
So in just 3 lines of code, you have your entire json serialized to java objects that you can use in your code.
Try
public void onResponse(JSONArray response) {
try {
if (response != null) {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = resultsArray.getAsJsonObject(i);
//get nid array
JSONArray nidJSONArray = jsonObject.getJSONArray("nid");
//get uid array
JSONArray uidJSONArray = jsonObject.getJSONArray("uid");
//get field_image array
JSONArray fieldImageJSONArray = jsonObject.getJSONArray("field_image");
//parse nid array
if (nidJSONArray != null) {
for (int i = 0; i < nidJSONArray.length(); i++) {
JSONObject jsonObject = nidJSONArray.getAsJsonObject(i);
String value = jsonObject.getString("value");
}
}
//parse uid array
if (uidJSONArray != null) {
for (int i = 0; i < uidJSONArray.length(); i++) {
JSONObject jsonObject = uidJSONArray.getAsJsonObject(i);
String targetId = jsonObject.getString("target_id");
String url = jsonObject.getString("url");
}
}
//parse field_image array
if (fieldImageJSONArray != null) {
for (int i = 0; i < fieldImageJSONArray.length(); i++) {
JSONObject jsonObject = fieldImageJSONArray.getAsJsonObject(i);
String targetId = jsonObject.getString("target_id");
String alt = jsonObject.getString("alt");
String title = jsonObject.getString("title");
String width = jsonObject.getString("width");
String height = jsonObject.getString("height");
String url = jsonObject.getString("url");
}
}
}
}
} catch(Exception e) {
Log.e("Error", e.getMessage());
}
}
here my jsonArray data like:
[{"LeadId":4,
"CoreLeadId":0,
"CompanyId":7,
"AccountNo":"5675",
"ScheduleOn":"2015-05-11T00:00:00"},
{"LeadId":7,
"CoreLeadId":2,
"CompanyId":8,
"AccountNo":"sample string 4",
"ScheduleOn":"2015-12-01T15:04:23.217"}]
i want to sort by dateandtime(ScheduleOn) and put into listview. below i side i send snnipt of my code where i set adapter. can we sort into listItemService. Please help me.
JSONArray jsonArray = dpsFunctionFlow.getAllServiceDetail("1");
listItemService = new Gson().fromJson(jsonArray.toString(),
new TypeToken<List<AppointmentInfoDto>>() {
}.getType());
mAdapter = new AdapterAppointment(getActivity(), listItemService);
listView.setAdapter(mAdapter);
You should be able to use Collections.sort(...) passing in a Comparator that will compare 2 AppointmentInfoDto objects.
Collections.sort(listItemService, new Comparator<AppointmentInfoDto>() {
#Override public int compare(AppointmentInfoDto l, AppointmentInfoDto r) {
// Compare l.ScheduleOn and r.ScheduleOn
}
}
/// Sort JSON By any Key for date
public static JSONArray sortJsonArray(JSONArray array,final String key, final boolean isCase) {
List<JSONObject> jsonsList = new ArrayList<JSONObject>();
try {
for (int i = 0; i < array.length(); i++) {
jsonsList.add(array.getJSONObject(i));
}
Collections.sort(jsonsList, new Comparator<JSONObject>() {
#Override
public int compare(JSONObject v_1, JSONObject v_2) {
String CompareString1 = "", CompareString2 = "";
try {
CompareString1 = v_1.getString(key); //Key must be present in JSON
CompareString2 = v_2.getString(key); //Key must be present in JSON
} catch (JSONException ex) {
// Json Excpetion handling
}
return CompareString1.compareTo(CompareString2);
}
});
} catch (JSONException ex) {
// Json Excpetion handling
}
return new JSONArray(jsonsList);
}
// _Sort JSON for any String Key value.........
public static JSONArray sortJsonArray(JSONArray array,final String key, final boolean isCase) {
List<JSONObject> jsonsList = new ArrayList<JSONObject>();
try {
for (int i = 0; i < array.length(); i++) {
jsonsList.add(array.getJSONObject(i));
}
Collections.sort(jsonsList, new Comparator<JSONObject>() {
#Override
public int compare(JSONObject v_1, JSONObject v_2) {
String CompareString1 = "", CompareString2 = "";
try {
CompareString1 = v_1.getString(key); //Key must be present in JSON
CompareString2 = v_2.getString(key); //Key must be present in JSON
} catch (JSONException ex) {
// Json Excpetion handling
}
return isCase ? CompareString1.compareTo(CompareString2) : CompareString1.compareToIgnoreCase(CompareString2);
}
});
} catch (JSONException ex) {
// Json Excpetion handling
}
return new JSONArray(jsonsList);
}
How can i extract the json below and save it in an arraylist.
{
"trains": {
"train": [
{
"#id": 1000000103,
"#version": 1,
"#status": "active",
"#name": "dffffff",
"#description": "ffffff half of the nineteenth century.",
"#city": "fff",
"#phone": "+230 595-1454",
"#email": "ffffr#mffc.mu",
"#website": "www4u",
"#latitude": -5.2882,
"#longitude": 3.499,
"#defaultLocale": "",
"#holes": 48,
"#par": 72,
"#slope": 0,
"#distance": 5.005273,
"circuits": {
"circuit": []
},
"localizations": {
"localization": []
}
},
{
"#id": 1000000105,
"#version": 1,
"#status": "active",
"#name": " xClub",
"#description": "",
"#city": " xlet",
"#phone": "+44465\t",
"#email": "",
"#website": "wweffl.com",
"#latitude": -2.040318,
"#longitude": 54548,
"#defaultLocale": "",
"#holes": 18,
"#par": 32,
"#slope": 0,
"#distance": 2441673,
"circuits": {
"circuit": []
},
"localizations": {
"localization": []
}
}
]
}
}
my working
try {
jobj_trouve_train = new JSONObject(reponse_trouve_train);
String jsonobj = jobj_trouve_golf.getString("trains");
//String jsonobj1 = jobj_trouve_golf.getString("train");
//jobj_trouve_train = new JSONObject(reponse_trouve_train);
//jsonArray = jobj_trouve_golf.getJSONArray("trains");
//jsonArray= new JSONArray(jsonobj);
//System.out.println("jsonArray "+jsonArray);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Try this..
try {
jobj_trouve_train = new JSONObject(reponse_trouve_train);
JSONObject jsonobj = jobj_trouve_train.getJSONObject("trains");
JSONArray jsonobj1 = jsonobj.getJSONArray("train");
for(int i = 0;i< jsonobj1.length();i++){
JSONObject jsonj = jsonobj1.getJSONObject(i);
System.out.println("#id "+jsonj.getString("#id"));
// Same for remaining all
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
You can use the Gson library developed by Google to parse Json into objects.
The reference is here:
https://code.google.com/p/google-gson/
And, a sample example is here:
JSON Parsing with GSON
JSONObject trains = jobj_trouve_train.getJSONObject("trains");
JSONArray trainArray = trains.getJSONArray("train");
JSONObject train1 = trainArray.getJSONObject(0);
...
if i didn't get confuse maybe this one will be right
JSONArray jasonArray = new JSONArray(result.getProperty("trains").toString());
for (int i = 0; i < jasonArray.length(); i++) {
JSONObject jsonObj = jasonArray.optJSONObject(i);
trainObject = new JSONObject(jsonObj.optString("train").toString());
int id = trainObject.optInt("id");
and so on..
}
public Object void toObject(String jsonMsg) throws JSONException {
JSONObject trains= (JSONObject) new JSONTokener(jsonMsg).nextValue();
if(trains.has("trains")){
JSONArray train = (JSONArray) new JSONTokener(object.getString("train")).nextValue();
for (int t = 0; t < jsonArray.length(); t++) {
String temp = jsonArray.getJSONObject(t).toString();
JSONObject object = (JSONObject) new JSONTokener(temp).nextValue();
if(object.has("#id"))
object.getString("#id");
// now similar procedure of reading
// read values and save it in an "object"
}
return savedObject;
}
-- tested, i have tried to modify code to match your JSON data. complete the rest.
I want to generate the following form
{
"dt": {
"DocumentElement": [
{
"CompanyID": "8",
"Question": "Who I M?",
"Answer": "dfsfdsfd"
},
{
"CompanyID": "8",
"Question": "Who I M?",
"Answer": "Chintan"
}
]
}
}
I have one arraylist which is dynamically filled with data and i also want the form in terms of dynamic. Here is my code:
JSONObject DocumentElementobj = new JSONObject();
JSONArray req = new JSONArray();
JSONObject reqObj = new JSONObject();
try {
for (int i = 0; i < OnLineApplication.mParserResults.size(); i++) {
reqObj.put("CompanyID", "8");
reqObj.put("Question",OnLineApplication.mParserResults.get(i).getQuestion());
reqObj.put("Answer",OnLineApplication.mParserResults.get(i).getAnswer());
}
DocumentElementobj.put( "DocumentElement", req );
System.out.println("Final "+DocumentElementobj.toString());
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
It outputs:
Final {"DocumentElement":[]}
EDIT
Thanks to all your response. As per you all responce i make code like below
JSONObject DocumentElementobj = new JSONObject();
JSONArray req = new JSONArray();
JSONObject reqObjdt = new JSONObject();
try {
for (int i = 0; i < OnLineApplication.mParserResults.size(); i++) {
JSONObject reqObj = new JSONObject();
reqObj.put("CompanyID", OnLineApplication.mParserResults.get(i).getCompanyId());
reqObj.put("Question",OnLineApplication.mParserResults.get(i).getQuestion());
reqObj.put("Answer",OnLineApplication.mParserResults.get(i).getAnswer());
req.put(reqObj);
}
DocumentElementobj.put( "DocumentElement", req );
reqObjdt.put("dt", DocumentElementobj);
System.out.println("Final "+reqObjdt.toString());
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
I get foramt which i want but in final string i get sequeence like below
{"dt":
{"DocumentElement":
[
{"Answer": "The Claims Representatives have a small role in return to work.","Question":"Return-to-Work Claim Issues. Please check the statement that best applies.","CompanyID":"8"},
{"Answer":"Poor","Question":"How would you describe the level of your general employee’s understanding of the impact of workers’ compensation costs on your organization?","CompanyID":"8"}]}}
it comes Answer first in sequence but i want to CompanyID first so what is issue in that?
You forgot to add JSONObject reqObj into JSONArray req. like req.put(reqObj);.
Modify your code block from for loop like
JSONObject reqObj = new JSONObject(); // Move inside the loop
reqObj.put("CompanyID", "8");
reqObj.put("Question",OnLineApplication.mParserResults.get(i).getQuestion());
reqObj.put("Answer",OnLineApplication.mParserResults.get(i).getAnswer());
req.put(reqObj); // ADDED HERE
You don't add the reqObj to req.
Do req.put(reqObj)
JSONObject documentElementobj = new JSONObject();
JSONArray req = new JSONArray();
try {
for (int i = 0; i < OnLineApplication.mParserResults.size(); i++) {
JSONObject reqObj = new JSONObject();
reqObj.put("CompanyID", "8");
reqObj.put("Question",OnLineApplication.mParserResults.get(i).getQuestion());
reqObj.put("Answer",OnLineApplication.mParserResults.get(i).getAnswer());
req.put(reqObj);
}
documentElementobj.put( "documentElement", req );
System.out.println("Final "+ documentElementobj.toString());
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Also, it is better to make your variables begin with a lowercase letter, usually.
One more thing, using a debugger will be effective in this case.
There is a very good Google Libray called gson which help you to create Json Object or Parse Json Object with very ease.
You need to add gson.jar file in your project.
For More details go through the below link.
https://sites.google.com/site/gson/gson-user-guide
Edited Answer:-
public class DocumentElement {
#Expose
private String CompanyID;
#Expose
private String Question;
#Expose
private String Answer;
public DocumentElement(String CompanyID, String Question, String Answer) {
this.CompanyID = CompanyID;
this.Question = Question;
this.Answer = Answer;
}
public String getCompanyID() {
return CompanyID;
}
public String getQuestion() {
return Question;
}
public String getAnswer() {
return Answer;
}
}
public class Data {
#Expose
private ArrayList<DocumentElement> DocumentElement;
public ArrayList<DocumentElement> getDocumentElement() {
return DocumentElement;
}
public void setDocumentElement(ArrayList<DocumentElement> DocumentElement) {
this.DocumentElement = DocumentElement;
}
}
public class ParentData {
#Expose
private Data dt;
public Data getDt() {
return dt;
}
public void setDt(Data dt) {
this.dt = dt;
}
}
And used like this to create JsonObject by help of gson.jar
ArrayList<DocumentElement> doc=new ArrayList<DocumentElement>();
DocumentElement doc1=new DocumentElement("8", "Who I M?", "Amit");
DocumentElement doc2=new DocumentElement("9", "Who I M?", "Gupta");
doc.add(doc1);
doc.add(doc2);
Data data=new Data();
data.setDocumentElement(doc);
ParentData parent=new ParentData();
parent.setDt(data);
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
String jsonObj = gson.toJson(parent);
System.out.println("createdJson:---"+jsonObj);
The Result are
{"dt":{"DocumentElement":[{"Answer":"Amit","CompanyID":"8","Question":"Who I M?"},{"Answer":"Gupta","CompanyID":"9","Question":"Who I M?"}]}}
Hope this will help you.
Use this code to fullfill your answer :
JSONObject jObj = new JSONObject("Your web Response");
JSONObject jObj1 = jObj.getJSONObject("dt");
JSONArray item = jObj.getJSONArray("DocumentElement");
for (int i = 0; i < item.length(); i++)
{
jObj_data = (JSONObject) item.get(i);
reqObj.put("CompanyID", jObj_data.getString("CompanyID"));
reqObj.put("Question",jObj_data.getString("Question"));
reqObj.put("Answer",jObj_data.getString("Answer"));
}