I am working on an app which I need to parse jsonarray. I have my json values in base64 and I need to decode strings to retrive data with decode String. Here is my code :
private class DecodeData extends AsyncTask<String, Void, String> {
#SuppressWarnings("unchecked")
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String response = params[0];
String keys = "";
String value = "";
String b64Value = "";
LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
try {
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
Iterator<String> it = array.getJSONObject(i).keys();
while (it.hasNext()) {
keys = (String)it.next();
value = (String)array.getJSONObject(i).get(keys);
b64Value = Base64.DecodeStrToStr(value);
Log.i("ASYNC TASK VALUE", b64Value);
map.put(keys, b64Value);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return map.toString();
}
I get only the first JSONObject and I need to get all JSONObject with all values. I can't use getString(name) because my json can have others keys. What am I doing wrong and why am I getting only the first JSONObject and not the others ?
json type :
[
{
"value": "ZG1WdVpISmxaR2tnTWpVZ1lYWnlhV3c4WW5JZ0x6NEtSMVZaUVU1QklFRk1UQ0JUVkVGUw==",
"date_create": "MjAxNC0wNC0yNSAwMDowMDowMA==",
"picture": "aHR0cDovL3dzLmFwcHMtcGFuZWwubmV0L2RhdGEvcGFsYWNpby8yNWF2cmlsLmpwZw==",
"link": "",
"title": "MjVhdnJpbA==",
"media": "",
"id_news": "MTA5NjI0",
"id_reference": "",
"type": "",
"id_categorie": "",
"date_event": "MjAxNC0wNC0yNSAwMDowMDowMA==",
"chapo": "",
"auteur": "",
"value_out": "dmVuZHJlZGkgMjUgYXZyaWxHVVlBTkEgQUxMIFNUQVI="
},
{
"value": "YzJGdFpXUnBJREkySUdGMmNtbHNQR0p5SUM4K0NrMUJVbFpKVGlCaGJtUWdSbEpKUlU1RVV3PT0=",
"date_create": "MjAxNC0wNC0yNiAwMDowMDowMA==",
"picture": "aHR0cDovL3dzLmFwcHMtcGFuZWwubmV0L2RhdGEvcGFsYWNpby8yNmF2cmlsMi5qcGc=",
"link": "",
"title": "MjZhdnJpbA==",
"media": "",
"id_news": "MTA5NjMx",
"id_reference": "",
"type": "",
"id_categorie": "",
"date_event": "MjAxNC0wNC0yNiAwMDowMDowMA==",
"chapo": "",
"auteur": "",
"value_out": "c2FtZWRpIDI2IGF2cmlsTUFSVklOIGFuZCBGUklFTkRT"
},
Here is what i am getting with my code :
RESPONSE :{date_create=MjAxNC0wNS0yNSAwMDowMDowMA==, link=, date_event=MjAxNC0wNS0yNSAwMDowMDowMA==, type=, value_out=ZGltYW5jaGUgMjUgbWFpRE9MQSBNSVpJSyBlbiBjb25jZXJ0, picture=aHR0cDovL3dzLmFwcHMtcGFuZWwubmV0L2RhdGEvcGFsYWNpby8yNW1haS5qcGc=, title=MjUgbWFp, id_reference=, chapo=, value=WkdsdFlXNWphR1VnTWpVZ2JXRnBQR0p5SUM4K0NqeGljaUF2UGdwRVQweEJJRTFKV2tsTElHVnVJR052Ym1ObGNuUT0=, id_news=MTA5NjM0, media=, auteur=, id_categorie=}
Anybody has an idea of how I can do ?
Thank you
Problem:
You are putting all results in the same Map. Each object in the JSONArray will erase the values of previous objects because the keys are the same.
In the end, you get only one value for each key.
Solution:
You need one map per JSON object in the array. You could use a list (or array) of Maps, for instance. Here is some code:
ArrayList<HashMap<String, String>> decodedArray = new ArrayList<>();
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
HashMap<String, String> map = new HashMap<>();
Iterator<String> it = array.getJSONObject(i).keys();
while (it.hasNext()) {
keys = (String) it.next();
value = (String) array.getJSONObject(i).get(keys);
b64Value = Base64.DecodeStrToStr(value);
Log.i("ASYNC TASK VALUE", b64Value);
map.put(keys, b64Value);
}
decodedArray.add(map);
}
Add you json value into model object I hope it would be helpful for you.
public class A {
private Vector<B> b = new Vector<B>();
public Vector<B> getB() {
return b;
}
public void addB(B b) {
this.b.add(b);
}
public class B{
private String value;
private String picture;
//add your paramatere here like link, title etc
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
}
}
Then after parsing value set into bean object like that.
A a = new A();
for (int i = 0; i < jsonArray.length(); i++) {
B b= a.new B();
JSONObject jsonObject= (JSONObject)jsonArray.get(i);
String value= jsonObject.getString("value");
jsonObject.getString("picture");
// get all value from json object set into b object
a.addB(b);
}
Related
I have some data provided from an API for example this is the data, this is just a part of the data, but this is the part that I need to access
"logo_url_string": null,
"name": "google",
"category_image": {
"id": 24,
"cover_url": {
"url": "http://",
"icon_circle": {
"url": "http://"
}
The question is how can I access the "url" inside cover_url thats inside category_image?, and so far I've been able to access it from a Model class with setter and getters and an adapter but I don't know how can I access data that is nested with setters and getters I have to do it with setters and getters because I have an adapter class where I get all the data into de cardview and then I load it to a recycler that is in a fragment, please any help would be great Thank you!
my model is like this
Business.java
public class Business {
private String name, description, email, website, logo_url_string,cover_url_string;
public Business(){}
public class Images{
}
public Business(String name, String logo_url_string) {
this.name = name;
this.logo_url_string = logo_url_string;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLogo_url_string() {
return logo_url_string;
}
public void setLogo_url_string(String logo_url_string) {
this.logo_url_string = logo_url_string;
}
And I access that data with and Adapter
Adapter.java
public class SearchHorizontalAdapter extends RecyclerView.Adapter<SearchHorizontalAdapter.ViewHolder> {
private ArrayList<Business> premiumsList;
Bitmap bitmap;
ImageView logo;
private Activity activity;
private int layoutMolde;
public SearchHorizontalAdapter(Activity activity, ArrayList<Business> list, int layout ) {
this.activity = activity;
this.premiumsList = list;
layoutMolde = layout;
}
#Override
public SearchHorizontalAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.search_high_layout, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(SearchHorizontalAdapter.ViewHolder holder, int position) {
// holder.mTitle.setText(premiumsList.get(position));
holder.mTitle.setText(premiumsList.get(position).getName());
//holder.mImg.setImageURI(Uri.parse(premiumsList.get(position).getLogo_url_string()));
// if( Glide.with(this.activity).load(premiumsList.get(position).getLogo_url_string())==null) {
// Glide.with(this.activity).load(premiumsList.get(position).getCategory_image()).into(holder.mImg);
// }
Glide.with(this.activity).load(premiumsList.get(position).getLogo_url_string()).into(holder.mImg);
}
#Override
public int getItemCount() {
return premiumsList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView mTitle;
public ImageView mImg;
public ViewHolder(View itemView) {
super(itemView);
mTitle = (TextView) itemView.findViewById(R.id.nom_business);
mImg= (ImageView) itemView.findViewById(R.id.img_business);
}
}
}
Try This,
try {
JSONObject objResult = new JSONObject(response);
String name = objResult.getString("name");
JSONObject category_image_obj=objResult.getJSONObject("category_image");
JSONObject cover_url_obj=category_image_obj.getJSONObject("cover_url");
String url = cover_url_obj.getString("url");
ArrayList premiumsList =new ArrayList<>();
premiumsList.add(new Business(name,url);
//call adapter here
} catch (JSONException e) {
e.printStackTrace();
}
IF your JSON response as below then you can parse to use below java code.
{
"contacts": [
{
"id": "c200",
"name": "Android Developer",
"email": "android.developer#gmail.com",
"address": "xx-xx-xxxx,x - street, x - country",
"gender" : "male",
"phone": {
"mobile": "+91 0000000000",
"home": "00 000000",
"office": "00 000000"
}
}
]
}
Java Code where you can parse your JSON. I hope you will get your answer.
#Override
protected Void jsonParsing(String jsonString) {
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Store a json string in string variable
String jsonStr = jsonString;
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("contacts");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String email = c.getString("email");
String address = c.getString("address");
String gender = c.getString("gender");
// Phone node is JSON Object
JSONObject phone = c.getJSONObject("phone");
String mobile = phone.getString("mobile");
String home = phone.getString("home");
String office = phone.getString("office");
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("id", id);
contact.put("name", name);
contact.put("email", email);
contact.put("mobile", mobile);
// adding contact to contact list
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
}
} else {
Log.e(TAG, "Couldn't get json from server.");
}
}
For more detail about JSON Parsing please read this documentation. Other read this tutorial that how to parse the JSON.
First of all your json is wrong. If your json is like this,
{
"logo_url_string":null,
"name":"google",
"category_image":{
"id":"24",
"cover_url":{
"url":"http://",
"icon_circle":{
"url":"http://"
}
}
}
}
Try this
try {
JSONObject ai=new JSONObject(response);
JSONObject cat_img=ai.getJSONObject("category_image");
int id=cat_img.getInt("id"); //you can get id here
JSONObject cat_url=cat_img.getJSONObject("cover_url");
String url=cat_url.getString("url"); //you can get url from here
ArrayList<Business> premiumsList=new ArrayList<>();
premiumsList.add(new Business(cat_img.getString("name"),url)); //add it to aaray
} catch (JSONException e) {
e.printStackTrace();
}
Furthermore you can use this for making getters and setters for
nested json.
EDIT after proper initialisation but everything works but I still get only the first object in "events" array. Why ?
I've an AsyncTask which connects to server to download JSON file and to get JSON array from there. The problem is that when I want to extract another data from the same array using for loop I got a null pointer exception. Why ? I am extracting the values "lat","lon","text" from array "events".
Here is how my JSON looks :
{
"current_ts": 1425907330,
"username": "guri",
"events": [
{
"id": 16591481,
"ts": 1425907325,
"lat": 48.17,
"lon": 17.13,
"likes": 5,
"text": "Poziar na hlavnej stanici",
"tags": "#poziar #stanica #hori",
"img": "2002-06-19.jpg"
},
{
"id": 47067411,
"ts": 1425907100,
"lat": 48.81,
"lon": 17.22,
"likes": 0,
"text": "V Bille je velky vypredaj",
"tags": [
{
"tag1": "#akcia",
"tag2": "#akcia"
}
],
"img": "DSC04934.jpg"
}
]
And here is a code snippet from my AsyncTask:
#Override
protected Void doInBackground(Void... params) {
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://guri.sk/mapped/mapped.json");
try {
// Locate the array name in JSON
event = jsonobject.getJSONArray("events");
for (int i = 0; i < event.length(); i++) {
jsonobject = event.getJSONObject(i);
lat2[i] = jsonobject.getDouble("lat");
lon2[i] = jsonobject.getDouble("lon");
text1[i] = jsonobject.getString("text");
number = i;
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Close the progressdialog
mProgressDialog.dismiss();
for (int i = 0; i < number; i++) {
mMap.addMarker(new MarkerOptions().position(new LatLng(lat2[i], lon2[i])).title(text1[i]));
}
}
How I initialize:
double[] lat2 = new double[10];
double[] lon2 = new double[10];
String[] text1 = new String[10];
Answer to your problem after edit:
If your JSON has two elements then after for loop value of number will be 1, and then in onPostExecute for loop will execute only for first element in array. So I think you should set value of number before for loop:
number = event.length();
for (int i = 0; i < event.length(); i++) {
jsonobject = event.getJSONObject(i);
lat2[i] = jsonobject.getDouble("lat");
lon2[i] = jsonobject.getDouble("lon");
text1[i] = jsonobject.getString("text");
}
The problem is that you can't directly use for whatever reason for loop in onPostExecute of AsyncTask. You have to wrap it in a method. Here is the code snippet that works:
protected Void doInBackground(Void... params) {
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://guri.sk/mapped/mapped.json");
try {
// Locate the array name in JSON
event = jsonobject.getJSONArray("events");
number = event.length();
for (int i = 0; i < event.length(); i++) {
jsonobject = event.getJSONObject(i);
lat2[i] = jsonobject.getDouble("lat");
lon2[i] = jsonobject.getDouble("lon");
text1[i] = jsonobject.getString("text");
//Log.e("TAG","lat2:"+lat2[i]+"lon2:"+lon2[i]);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Close the progressdialog
mProgressDialog.dismiss();
placeMarkers();
}
}
public void placeMarkers(){
for (int i = 0; i < number; i++) {
Log.e("TAG","lat2:"+lat2[i]+"lon2:"+lon2[i]);
mMap.addMarker(new MarkerOptions().position(new LatLng(lat2[i], lon2[i])).title(text1[i]));
}
}
I want to get two json array from remote url
I am using AsyncTask to do that but i can't get any data !
#Override
protected Void doInBackground(String... params) {
try {
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
String json = jParser.getJSONFromUrl(params[0]);
// Getting Array of Contacts
data = new JSONArray(json);
JSONArray cities = data.getJSONArray();
// looping through All cities
for (int i = 0; i < cities.length(); i++) {
JSONObject e = cities.getJSONObject(i);
String ci_name = e.getString("ct_name");
String ci_web_id = e.getString("ct_id");
db.addCity(ci_name, ci_web_id);
db.closeDatabase();
}
JSONArray districts = data.getJSONArray(1);
// looping through All districts
for (int i = 0; i < districts.length(); i++) {
JSONObject e = districts.getJSONObject(i);
String di_name = e.getString("ar_name");
String di_web_id = e.getString("ar_id");
db.addDistrict(di_name, di_web_id);
db.closeDatabase();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
The return data is like that :
{"city":[
{"ct_id":"1432","ct_name":"\u062e\u0645\u064a\u0633 \u0645\u0634\u064a\u0637","ct_hide":"0","ct_ord":"0","ct_created":"0"},
{"ct_id":"1434","ct_name":"\u0639\u0633\u064a\u0631","ct_hide":"0","ct_ord":"0","ct_created":"0"},{"ct_id":"1435","ct_name":"\u0627\u0644\u0645\u0646\u0637\u0642\u0629 \u0627\u0644\u0634\u0631\u0642\u064a\u0629","ct_hide":"0","ct_ord":"0","ct_created":"0"}
], "area":[
{"ar_id":"1422","ar_name":"\u0627\u0644\u0645\u062f\u064a\u0646\u0629 \u0627\u0644\u0645\u0646\u0648\u0631\u0647","ar_hide":null,"ar_ord":null,"ar_created":null}, {"ar_id":"1433","ar_name":"\u0646\u062c\u0631\u0627\u0646","ar_hide":null,"ar_ord":null,"ar_created":null}]
}
Your json is a JSONObject not a JSONarray.
This
data = new JSONArray(json);
is wrong.
{ // json object node
"city": [ // json array city
{ // json object
"ct_id": "1432",
"ct_name": "خميس مشيط",
"ct_hide": "0",
"ct_ord": "0",
"ct_created": "0"
},
{
"ct_id": "1434",
"ct_name": "عسير",
"ct_hide": "0",
"ct_ord": "0",
"ct_created": "0"
},
{
"ct_id": "1435",
"ct_name": "المنطقة الشرقية",
"ct_hide": "0",
"ct_ord": "0",
"ct_created": "0"
}
],
"area": [ // json array area
{
"ar_id": "1422",
"ar_name": "المدينة المنوره",
"ar_hide": null,
"ar_ord": null,
"ar_created": null
},
{
"ar_id": "1433",
"ar_name": "نجران",
"ar_hide": null,
"ar_ord": null,
"ar_created": null
}
]
}
To parse
JSONObject jb = new JSONObject(json);
JSONArray city = jb.getJSONArray("city");
for(int i=0;i<city.length();i++)
{
JSONObject jb1 = city.getJSONObject(i);
String id = jb1.getString("ct_id");
String name = jb1.getString("ct_name");
String hide = jb1.getString("ct_hide");
String ord = jb1.getString("ct_ord");
String created = jb1.getString("ct_ord");
Log.i("city id is",id);
}
JSONArray area = jb.getJSONArray("area");
for(int i=0;i<area.length();i++)
{
JSONObject jb1 = area.getJSONObject(i);
String id = jb1.getString("ar_id");
String name = jb1.getString("ar_name");
String hide = jb1.getString("ar_hide");
String ord = jb1.getString("ar_ord");
String created = jb1.getString("ar_ord");
Log.i("Area id is",id);
}
You could also consider using gson to parse json to java objects
http://code.google.com/p/google-gson/
I don't see any request to remote url. How do you get data from your server?
Generally, it looks like this:
public void execute() {
final AndroidHttpClient client = AndroidHttpClient.newInstance("TAG");
try {
HttpUriRequest request = getRequest();
HttpResponse response = client.execute(request);
final int code = response.getStatusLine().getStatusCode();
Log.d("TAG", "Server returns " + code);
if (code == HttpStatus.SC_OK) {
String json = EntityUtils.toString(response.getEntity());
handleResult(json);
}
} catch (IOException e) {
Log.e("TAG", "Failed to execute response", e);
}
}
private void handleResult(String json) {
try {
JSONObject jObject = new JSONObject(json);//your response is not an array
JSONArray content = jObject.getJSONArray("city")
final int count = content.length();
for (int i = 0; i < count; i++) {
JSONObject city = content.getJSONObject(i);
Log.d("TAG", city.getString("ct_id"));
}
} catch (JSONException e) {
Log.e("TAG", "Failed to obtain json", e);
}
}
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"));
}
I have a json file formatted like this (only the actual file has no whitespace):
{
"main": [
{
"sections": [
"sec1",
"sec2"
],
"title": "Section List 1"
},
{
"sections": [
"sec3",
"sec4",
"sec5"
],
"title": "Section List 2"
}
],
"sections": {
"sec1": {
"products": [
"prod1",
"prod2"
]
},
"sec2": {
"products": [
"prod3"
]
}
},
"products": {
"prod1": {
"url": "url1.gif",
"title": "Product 1"
},
"prod2": {
"url": "url2.gif",
"title": "Product 2"
},
"prod3": {
"url": "url3.gif",
"title": "Product 3"
}
}
}
When I attempt to send the data for that file into JSONObject, the JSONObject being loaded only contains the final object in the top list, in this case "products". Right now, my code to load the JSONObject is this:
JSONObject dlResult = new JSONObject(new Scanner(cnxn.getInputStream()).nextLine());
I've also tried storing the data in a String first and giving that to the JSONObject constructor, I've tried giving that String to a JSONTokener first, and giving that tokener to the JSONObject constructor. Both the String and the JSONTokener contain the entire file, but once it gets put into the JSONObject, it's always the same thing - "main" and "sections" get cut out, and only "products" remains.
Here's the rest of my relevant code:
public class MapsListFragment extends ListFragment
{
private static JSONObject mDlResult;
private ArrayAdapter<MapInfo> mMapListAdapter = null;
private class MapInfo
{
private String mText;
private String mURL;
MapInfo(String inText, String inURL)
{
mText = inText;
mURL = inURL;
}
public String URL()
{
return mURL;
}
#Override
public String toString()
{
return mText;
}
}
public class MapsListUpdater extends AsyncTask<String, String, JSONObject>
{
private static final String URL = "http://jsonURL/products.json";
private Date lastUpdate;
#Override
protected JSONObject doInBackground(String... inObjects)
{
Date ifModifiedSince = lastUpdate;
try
{
HttpURLConnection cnxn = (HttpURLConnection) new URL(URL).openConnection();
if (ifModifiedSince != null)
cnxn.setIfModifiedSince(ifModifiedSince.getTime());
cnxn.connect();
if (cnxn.getResponseCode() != HttpURLConnection.HTTP_NOT_MODIFIED)
{
mDlResult = new JSONObject(new Scanner(cnxn.getInputStream()).nextLine());
}
cnxn.disconnect();
}
catch (Exception e)
{
boolean check = true;
}
return mDlResult;
}
#Override
protected void onPostExecute(JSONObject result)
{
super.onPostExecute(result);
try
{
// This is really ugly and brute-forcey, but it's the only way I could get JSONObjects populated with ALL the data!
/*String[] tryThis = mDlResult.split(",\"sections\":");
tryThis[0] += '}';
tryThis[1] = tryThis[1].substring(0, tryThis[1].indexOf("]}},\"products\":"));
tryThis[1] = "{\"sections\":" + tryThis[1] + "]}}}";*/
JSONObject mainObj = mDlResult.getJSONObject("main");//new JSONObject(mDlResult);
JSONArray mainArray = mainObj.getJSONArray("main");
Vector<String> titles = new Vector<String>();
mMapListAdapter.clear();
for (int i = 0; i < mainArray.length(); i++)
{
JSONObject object = mainArray.getJSONObject(i);
String title = object.getString("title");
if(!titles.contains(title))
{
titles.add(title);
mMapListAdapter.add(new MapInfo(object.getString("title"), null));
}
}
}
catch (Exception e)
{
boolean check = true;
}
}
}
}
I feel a little foolish now. As it turns out, the JSONObject was getting EXACTLY what I asked it for... only the objects within it were getting reordered, so I couldn't see the first 2 objects in my debugger!
Try reading it into a JSONArray and let me know how you get on:
JSONArray dlResult = new JSONArray(cnxn.getInputStream());