I have a JSON string and U want to get the name and add fields. I've tried to use several libraries and follow many tutorials, but was unsuccessful.
I thing my problem is that i have several arrays together...
inputLine =
{"posts":[
{"post":{
"name":"name1",
"add":"add1"}},
{"post":{
"name":"name2",
"add":"add2"}}
]
}
JSONObject obj_posts = new JSONObject(inputLine);
JSONArray menuitemArray = obj_posts.getJSONArray("posts");
JSONObject obj_post = new JSONObject(menuitemArray.getJSONObject(0).toString());
JSONObject menuitem = obj_post.getJSONObject("post");
JSONArray obj_post1 = menuitem.names();
At this point I can only access the key name and add, not the values.
JSONObject obj_posts = new JSONObject(inputLine);
JSONArray menuitemArray = obj_posts.getJSONArray("posts");
JSONObject obj_post = menuitemArray.getJSONObject(0);
JSONObject menuitem = obj_post.getJSONObject("post");
String postName = menuItem.getString("name");
String postAdd = menuItem.getString("add");
The below code should work:
System.out.println(menuitem.get(obj_post1.getString(0)));//Output name1
System.out.println(menuitem.get(obj_post1.getString(1)));//Output add1
You need to import "org.json.JSONArray" , " org.json.JSONException", "org.json.JSONObject"
Also throws JSONException.
String obj_post1_name = "";
String obj_post1_add = "";
String obj_post2_name = "";
String obj_post2_add = "";
String inputLine =
" {\"posts\":[{\"post\":{\"name\":\"name1\",\"add\":\"add1\"}},{\"post\":{\"name\":\"name2\",\"add\":\"add2\"}}]}";
JSONObject obj_posts = new JSONObject(inputLine);
JSONArray menuitemArray = obj_posts.getJSONArray("posts");
JSONObject obj_post1 =(menuitemArray.getJSONObject(0));
JSONObject obj_post2 =(menuitemArray.getJSONObject(1));
JSONObject menuitem = obj_post1.getJSONObject("post");
JSONObject menuitem2 = obj_post2.getJSONObject("post");
obj_post1_name= menuitem.getString("name");
obj_post1_add= menuitem.getString("add");
obj_post2_name= menuitem2.getString("name");
obj_post2_add= menuitem2.getString("add");
or you can use loop after:
JSONArray menuitemArray = obj_posts.getJSONArray("posts");
JSONObject obj_posts;
JSONObject menuitem;
for(int i=0;i<menuitemArray.length();i++){
obj_posts= menuitemArray.getJSONObject(i);
menuitem = obj_post1.getJSONObject("post");
menuitem.getString("name");
menuitem.getString("add");
}
Related
The data on server I want to retrieve, data in JSON format but problem is that I want to retrieve only data having specific CHEF_NAME from JSON array.I am using Android Studio.
JSON Array
[{"status":"Success","recpie":[{"id":"162","image":"1580130013.png","cat_id":"17","name":"Tikka Boti Mix Recipe","chef_name":"Mehran","link":"https:\/\/www.youtube.com\/watch?v=sbPNGHIOpQY","uvlink":"","like":"2","view":"227"},{"id":"168","image":"1580211123.png","cat_id":"17","name":"Seekh Kabab Paratha Roll Recipe","chef_name":"Mehran","link":"https:\/\/www.youtube.com\/watch?v=q36Syxhjg3o","uvlink":"","like":"19","view":"158"},{"id":"176","image":"recipe_1583154151.jpg","cat_id":"17","name":"Windows","chef_name":"Imran Ahmed","link":"","uvlink":"","like":"2","view":"119"},{"id":"190","image":"recipe_1584214019.jpg","cat_id":"17","name":"Chicken Broast","chef_name":"Imran Developer","link":"","uvlink":"http:\/\/billing.synctechsol.com\/video\/VID-20200112-WA0020.mp4","like":"3","view":"108"},{"id":"161","image":"1580309239.png","cat_id":"14","name":"Sindhi Biryani Mix Recipe","chef_name":"Mehran","link":"https:\/\/www.youtube.com\/watch?v=OUG7gYTrnEk","uvlink":"","like":"4","view":"104"},{"id":"182","image":"recipe_1584126527.jpeg","cat_id":"17","name":"Broast","chef_name":"Imran Developer","link":"","uvlink":"","like":"1","view":"64"},{"id":"198","image":"recipe_1584737360.jpeg","cat_id":"17","name":"Distribution Board","chef_name":"Imran Ahmed","link":"","uvlink":"http:\/\/billing.synctechsol.com\/video\/VID-20200219-WA0035.mp4","like":"7","view":"60"},{"id":"191","image":"recipe_1584260119.png","cat_id":"17","name":"ggbvn","chef_name":"Imran Developer","link":"","uvlink":"http:\/\/billing.synctechsol.com\/video\/VID-20200315-WA0001.mp4","like":"1","view":"58"},{"id":"163","image":"1580134470.png","cat_id":"15","name":"Achar Gosht Mix Recipe","chef_name":"Mehran","link":"https:\/\/www.youtube.com\/watch?v=5EQWOSRpzHg","uvlink":"","like":"8","view":"54"},{"id":"101","image":"1580210522.png","cat_id":"12","name":"Fish Fry Mix Recipe","chef_name":"Mehran","link":"https:\/\/www.youtube.com\/watch?v=GeSloGLoPMk","uvlink":"","like":"9","view":"50"},{"id":"178","image":"recipe_1583407824.jpg","cat_id":"17","name":"uhnbj","chef_name":"hi igh","link":"","uvlink":"","like":"0","view":"47"},{"id":"177","image":"recipe_1583234674.jpeg","cat_id":"17","name":"Kabuli Pulao","chef_name":"Imran Ahmed","link":"","uvlink":"","like":"0","view":"46"}]}]
Java Code
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String status = jsonObject.getString("status");
if (status.equals("Success")) {
JSONArray recipe = jsonObject.getJSONArray("recpie");
Log.e("Lenght", String.valueOf(recipe.length()));
for (int i = 0; i < recipe.length(); i++) {
JSONObject jsonObject1 = recipe.getJSONObject(i);
SearchGetSet searchGetSet = new SearchGetSet();
String id = jsonObject1.getString("id");
String image = jsonObject1.getString("image");
String cat_id = jsonObject1.getString("cat_id");
String name = jsonObject1.getString("name");
String chef_name = jsonObject1.getString("chef_name");
String link = jsonObject1.getString("link");
String uvlink = jsonObject1.getString("uvlink");
String like = jsonObject1.getString("like");
String view = jsonObject1.getString("view");
searchGetSet.setId(id);
searchGetSet.setRec_name(name);
searchGetSet.setRec_image(image);
searchGetSet.setLikes(like);
searchGetSet.setCat_id(cat_id);
searchGetSet.setChef_name(chef_name);
searchGetSet.setLink(link);
searchGetSet.setUVlink(uvlink);
searchGetSet.setView(view);
searchList.add(searchGetSet);}}
Create and add your searchGetSet object only if the chef_name is matching the name you're searching.
My guess is (I don't know Java), you've to use a simple if-statement, while looping :
for (int i = 0; i < recipe.length(); i++) {
JSONObject jsonObject1 = recipe.getJSONObject(i);
SearchGetSet searchGetSet = null; // Do not create your searchGetSet() object yet.
String chef_name = jsonObject1.getString("chef_name");
// Check the chef's name is 'John'.
if (chef_name.equals('John')) {
String id = jsonObject1.getString("id");
String image = jsonObject1.getString("image");
String cat_id = jsonObject1.getString("cat_id");
String name = jsonObject1.getString("name");
// ...
searchGetSet = new SearchGetSet();
searchGetSet.setId(id);
searchGetSet.setRec_name(name);
searchGetSet.setRec_image(image);
// ...
// Let's add the result we have found.
searchList.add(searchGetSet);
}
}
As title said I'm new to JSON and I can't get out of my problem. I'm working on this error for 1 week I'm really desperate to get out.
My error :
JSONException: Value [{"data":"11-13-2017","numeVanzator":"Clau","numarClient":0}] at jsonData of type java.lang.String cannot be converted to JSONArray
My JSON:
{
"jsonData" : {
"11-13-2017" : {
"Clau" : {
"-KyokKjL9UQpsfKZYZqM" : [ {
"pret" : "80",
"produs" : "Shirt",
"produsId" : "-Kyok58s0dOAnVOnbJPk"
} ]
}
}
}
}
I looked over tutorials on StackOverFlow but absolutely no solution.
My code :
private void writeJSON(String metodaPlata) throws JSONException {
String numeVanzator = SharedPreference.getString(this, SharedPreference.USER_DATA, SharedPreference.NUME_VANZATOR, "");
String jsonDataFromShared = SharedPreference.getString(this, SharedPreference.APP_DATA, SharedPreference.JSON_DATA, "");
int totalPrice = 0;
for(VanzatorProduse v : Util.getInstance().getVanzatorProduse())
{
int vPrice = Integer.parseInt(v.getPret());
totalPrice = totalPrice + vPrice;
}
String pretTotal = Integer.toString(totalPrice);
String produseSelectate = Integer.toString(listaProdusePreview.getAdapter().getCount());
JSONObject jsonData;
JSONArray dateJSON;
JSONObject obj;
JSONArray arrayForList;
if (jsonDataFromShared.equals("")) {
jsonData = new JSONObject();
dateJSON = new JSONArray();
obj = new JSONObject();
arrayForList = new JSONArray();
JSONObject objListaSiModalitate = new JSONObject();
// arrayForList.put(stock_list.toString());
objListaSiModalitate.put("lista", new JSONArray(Util.getInstance().getVanzatorProduse()));
objListaSiModalitate.put("metodaPlata", metodaPlata);
obj.put("data", getDate(calendarData.getTimeInMillis()));
obj.put("numeVanzator", numeVanzator);
obj.put("numarClient", numarVanzare);
dateJSON.put(obj);
jsonData.put("jsonData", dateJSON.toString());
SharedPreference.putString(this, SharedPreference.APP_DATA, SharedPreference.JSON_DATA, jsonData.toString());
} else {
jsonData = new JSONObject(jsonDataFromShared);
dateJSON = jsonData.getJSONArray("jsonData");
obj = new JSONObject();
JSONObject objListaSiModalitate = new JSONObject();
objListaSiModalitate.put("metodaPlata", metodaPlata);
obj.put("produseSelectate", produseSelectate);
obj.put("sumaProduse", pretTotal);
obj.put("data", getDate(calendarData.getTimeInMillis()));
obj.put("numeVanzator", numeVanzator);
obj.put("numarClient", numarVanzare);
dateJSON.put(obj);
jsonData.put("jsonData", dateJSON);
System.out.println("jsonData" + dateJSON);
SharedPreference.putString(this, SharedPreference.APP_DATA, SharedPreference.JSON_DATA, jsonData.toString());
}
}
Please help me I have no idea what to idea even if I look over tutorials.
I think your json parsing will be,
try {
JSONObject jsonObject = new JSONObject("jsonData");
JSONObject jsonObject1 = jsonObject.getJSONObject("11-13-2017");
JSONObject jsonObject2 = jsonObject1.getJSONObject("Clau");
JSONArray jsonArray = jsonObject2.getJSONArray("-KyokKjL9UQpsfKZYZqM");
JSONObject jsonObject3 = (JSONObject) jsonArray.getJSONObject(0);
String string = jsonObject3.getString("pret");
String string1 = jsonObject3.getString("produs");
String string2 = jsonObject3.getString("produsId");
} catch (JSONException e) {
e.printStackTrace();
}
Error causes from this line
jsonData.put("jsonData", dateJSON.toString());
Here dateJSON.toString() store the string value to jsonData variable. jsonData is JsonObject.
Then You try to retrieve JsonArray from string
jsonData = new JSONObject(jsonDataFromShared); //This line convert your string to jsonobject.
dateJSON = jsonData.getJSONArray("jsonData");
EDITED
If you want to retreive array from dateJson object
Replace this line
jsonData.put("jsonData", dateJSON.toString());
To
jsonData.put("jsonData", dateJSON);
I have a JSON Object which converted into String and saved into database .But when i am trying to get it back it is throwing exception.My object is something like that...
{"COLUMN":["Type","Sub Type","F.P.","P.P.","Process","Due To Start"]}
How can we get the data back in Normal form?
My Java Code is.....
JSONObject obj = new JSONObject();
JSONArray the_json_array = obj.getJSONArray(userReorderOption);
int size = the_json_array.size();
ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
for (int i = 0; i < size; i++) {
JSONObject another_json_object = the_json_array.getJSONObject(i);
arrays.add(another_json_object);
}
And Exception i am getting....
net.sf.json.JSONException: JSONObject["{\"TASKLIST_COLUMN_REORDER\":[\"Type\",\"Sub Type\",\"F.P.\",\"P.P.\",\"Process\",\"Due To Start\"]}"] is not a JSONArray.
And this is java Code how i am creating JSON Object and saving into database...
String userReorderSelection;
Set set = new LinkedHashSet(userReorderSelection);
JSONObject json = new JSONObject();
json.accumulate("COLUMN", set);
saveJSONObj("PrimaryKeyColumn", json.toString());
Thanks Tichodroma,
But as i told i am using net.sf.json.JSONObject class and above things we can achieve from this class too..What i did to solve the above issue?...Please have a look on the Java code...
JSONObject jsonObj = new JSONObject();
JSONObject obj = jsonObj.fromObject(userReorderOption);
JSONArray columnName = (JSONArray) obj.get("COLUMN");
for (int i = 0; i < columnName.size(); i++) {
System.out.println(columnName.getString(i));
}
This code work fine for me with my Json Jar**(net.sf.json)**
Your JSON is not a JSONArray.
A JSONArray is an ordered sequence of values.
You have a JSONObject.
A JSONObject is an unordered collection of name/value pairs.
Edit:
Using the JSON implementation from org.codehaus.jettison.json, you can do this:
String json = "{\"COLUMN\":[\"Type\",\"Sub Type\",\"F.P.\",\"P.P.\",\"Process\",\"Due To Start\"]}";
JSONObject obj = new JSONObject(json);
JSONArray column = (JSONArray) obj.get("COLUMN");
for (int i = 0; i < column.length(); i++) {
final String field = column.getString(i);
System.out.println(field);
}
Result:
Type
Sub Type
F.P.
P.P.
Process
Due To Start
I have the following array returned to my JAVA Android application from PHP:
Array ( [0] => Array ( [referral_fullname] => Name 1 [referral_balance] => 500 ) [1] => Array ( [referral_fullname] => Name 2 [referral_balance] => 500 ) );
In Java they above array looks like this:
{"0":{"referral_fullname":"Name 1","referral_balance":"500"},"1":{"referral_fullname":"Name 2","referral_balance":"500"}};
For a simple JSONObject I'm using:
JSONTokener tokener = new JSONTokener(result.toString());
JSONObject finalResult = new JSONObject(tokener);
referral_fullname = finalResult.getString("referral_fullname");
but for an array of objects I don't know!
String str = your Json-> apply to.String();
JSONObject jObject = new JSONObject(str);
Map<String,String> map = new HashMap<String,String>();
Iterator iter = jObject.keys();
while(iter.hasNext()){
String key = (String)iter.next();
String value = jObject .getString(key);
map.put(key,value);
}
Your Json Syntax is wrong , JSONArray should be like this :
["0":{"referral_fullname":"Name 1","referral_balance":"500"},"1":{"referral_fullname":"Name 2","referral_balance":"500"}];
and to parse a JsonArray that contains some JSONObject , try this :
//parse the result
JSONObject jsonResult = null;
JSONArray arrayResult = null;
ArrayList<YourObject> listObjects = null;
try {
arrayResult = new JSONArray(result);
if(arrayResult != null) {
listObjects = new ArrayList<YourObject>();
int lenght = arrayResult.length();
for(int i=0; i< lenght; i++) {
JSONObject obj = arrayResult.getJSONObject(i);
YourObject object = new YourObject(obj);
listObjects.add(object);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
And add a constructor in your Class YourObject to convert your Json to an instance :
public YourObject(JSONObject json) {
if (!json.isNull("referral_fullname"))
this.referral_fullname = json.optString("referral_fullname", null);
if (!json.isNull("referral_balance"))
this.referral_balance = json.optString("referral_balance", null);
}
You should use
JSONArray finalResult = new JSONArray(tokener);
if you can. You structure is now an object with two fields, 0 and 1, which contains another object. You have to get an array of object in place of this composite object if you want to iterate easily like
JSONObject jso;
for(int i = finalResult.lenght-1; i >=0; i--){
jso = finalResult.get(i);
// jso == {"referral_fullname":"Name 1","referral_balance":"500"}
[whatever]
}
Try this.............
final JSONArray result_array = json.getJSONArray("result");
for (int i = 0; i < result.length(); i++) {
JSONObject joObject = result_array.getJSONObject(i);
String jName = joObject.get("referral_fullname").toString();
String jbalance = joObject.get("referral_balance").toString();
}
First make an JSON object and see then in inner level what you have if you have array then fetch array.
You need to make JSON object first. For example, if resp is a String (for example coming as http response)
JSONObject jsonObject = new JSONObject(resp);
jsonObject may contains other JSON Objects or JSON array. How to convert the JSON depends on the response.
If arraykey is a array inside the JSON objects then we can get list of array by the following way.
JSONArray arr = jsonObject.getJSONArray("arraykey");
Check the length of arr, if it is greater than 0 then it contains JSON objects or JSON array depending the data.
There is a complete example with some explanation about JSON String to JSON array can be found at
http://www.hemelix.com/JSONHandling
I have written java code for generating json of my searched data from file.But its not generating exact JsonArray. Its like
[{"item":"1617"},{"item":"1617"}]
instead of
[{"item":"747"},{"item":"1617"}].
Here 1617 is last item which is fetched from file.
JSONArray ja = new JSONArray();
JSONObject jo = new JSONObject();
while (products.readRecord())
{
String productID = products.get("user");
int j = Integer.parseInt(productID);
if(j == userId) {
itemid = products.get("item");
jo.put("item",itemid);
ja.add(jo);
}
}
out.println(ja);
products.close();
you are actually creating one jSONobject object to handle two objects, shouldn't you need to create JSONObjects in the while loop? something like this, so every iteration in while loop will create a new JSONObject and add it to JSONArray
JSONArray ja = new JSONArray();
while (products.readRecord())
{
String productID = products.get("user");
int j = Integer.parseInt(productID, 10);
if(j == userId)
{
JSONObject jo = new JSONObject();
itemid = products.get("item");
jo.put("item", itemid);
ja.add(jo);
}
}
out.println(ja);
products.close();
Extra:
i am not sure how java does conversion for string to integer, but i think you should always specify radix when using parseInt so the strings like '09' will not be treated as octal value and converted to wrong value (atleast this is true in javascript :))
Integer.parseInt(productID, 10);
You must re-instantiate your JSonObject inside the loop because when you modify it you modify the underlying object which is referenced several times by your array. Move your JSONObject jo = new JSONObject(); inside the loop and it should work fine.
Place JSONObject jo = new JSONObject(); inside the loop:
while (products.readRecord())
{
JSONObject jo = new JSONObject();
String productID = products.get("user");
int j = Integer.parseInt(productID);
// etc
}