I am having a JSON string (jsonString):
["[{"Name":"name.pdf","ValueDate":"2016-08-30T22:00:00+0000"}]"]
jsonString is an array and I have to retrieve Name elements from it
I am using below code:
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
System.out.println("jsonString"+ jsonString);
JSONObject jsonObj = new JSONObject();
JSONArray lineItems = jsonObj.getJSONArray(jsonString);
for (Object o : lineItems) {
JSONObject jsonLineItem = (JSONObject) o;
String name = jsonLineItem.getString("Name");
String valueDate = jsonLineItem.getString("ValueDate");
}
But I am getting below error:
net.sf.json.JSONException: JSONObject["[\"[{\"Name\":\"name.pdf\",\"ValueDate\":\"2016-08-30T22:00:00+0000\"}]\"]"] is not a JSONArray.
at net.sf.json.JSONObject.getJSONArray(JSONObject.java:2038) ~[json-lib-2.4.jar:na]
Can anybody help me in this?
Update:
I used JSONArray lineItems = JSONArray.fromObject(jsonString); to come over above error suggested by qxz and used below code to loop through JSONArray
JSONArray lineItems = JSONArray.fromObject(listDocToSendJson);
for (int i = 0; i < lineItems.size(); i++) {
JSONObject jsonObj = lineItems.getJSONObject(i);
String name = jsonObj.getString("Name");
String valueDate = jsonObj.getString("ValueDate");
}
or
for (Object object : lineItems) {
JSONObject jsonStr = (JSONObject)JSONSerializer.toJSON(object);
System.out.println(" name is --"+jsonStr.get("Name"));
System.out.println(" value is ---"+jsonStr.get("ValueDate"));
}
Both are giving errors
net.sf.json.JSONException: JSONArray[0] is not a JSONObject.
java.lang.ClassCastException: net.sf.json.JSONArray cannot be cast to net.sf.json.JSONObject
Please suggest how I can fix this.
To convert a JSON array in a string to a JSONArray, use JSONArray.fromObject:
JSONArray lineItems = JSONArray.fromObject(jsonString); // converts String to JSONArray
for (Object o : lineItems) {
...
}
JSONObject.getJSONArray is for retrieving a given key of a JSON object as an array.
["[{"Name":"name.pdf","ValueDate":"2016-08-30T22:00:00+0000"}]"]
The string does not comply to JSON syntax.
Remove leading [" and trailing "] first then it will be looking like correct JSON array.
This is not valid
["[{"Name":"name.pdf","ValueDate":"2016-08-30T22:00:00+0000"}]"]
but this one is valid
[[{"Name":"name.pdf","ValueDate":"2016-08-30T22:00:00+0000"}]]
The quote ruins the validy of the String. And inorder to parse it you need to loop twice.
JSONArray lineItems = new JSONArray(listDocToSendJson);
for (int i = 0; i < lineItems.size(); i++) {
JSONArray jsonArr = lineItems.getJSONArray(i);
for (int x = 0; x < jsonArr.size(); x++) {
JSONObject jsonObj = lineItems.getJSONObject(i);
String name = jsonObj.getString("Name");
String valueDate = jsonObj.getString("ValueDate");
}
}
}
Try this it should work .. just to add your json string had a problem i have corrected that as well it should as
[{"Name":"name.pdf","ValueDate":"2016-08-30T22:00:00+0000"}]
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class JSONTest {
public static void main(String[] args) {
String jsonString ="[{\"Name\":\"name.pdf\",\"ValueDate\":\"2016-08-30T22:00:00+0000\"}]";
System.out.println("jsonString" + jsonString);
try {
JSONArray jsonArray = new JSONArray(jsonString);
for (int i=0;i<jsonArray.length();i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
String name = jsonObj.getString("Name");
String valueDate = jsonObj.getString("ValueDate");
System.out.println("Name : "+name + "ValueDate : "+valueDate);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Finally I am able to retrieve elements from JSON string looking like this
["[{\"Name\":\"name.pdf\",\"ValueDate\":\"2016-08-30T22:00:00+0000\"}]"]
I used json.jar
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
jsonStringList = jsonStringList.substring(2, jsonStringList.length()-2); //removed brackets and double quotes
jsonStringList = jsonStringList.replaceAll("\\\\", ""); //remove extra backslashes
System.out.println("jsonStringList "+jsonStringList); //valid json //[{"Name":"name.pdf","ValueDate":"2016-08-30T22:00:00+0000"}]
try {
JSONArray jsonArray = new JSONArray(jsonStringList);
for (int i=0;i<jsonArray.length();i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
String name = jsonObj.getString("Name");
String valueDate = jsonObj.getString("ValueDate");
System.out.println("Name : "+name + "ValueDate : "+valueDate);
}
Thank you all for great help. :)
Related
Okay, I'm struggling here. I am getting the following JSON formated string from my php server (called "result") (edited! I was missing a curly brace at the end):
{"L1":[{"UserName":"User1","Avatar":"1"},{"UserName":"User2","Avatar":"2"},{"UserName":"User3","Avatar":"3"}],"L2":[{"UserName":"User4","Avatar":"4"},{"UserName":"User5","Avatar":"5"}]}
I'm trying to extract an ArrayList with the Avatar numbers from the L1 object(?). But I get an error
org.json.JSONException: Value
[{"UserName":"User1","Avatar":"1"},{"UserName":"User2","Avatar":"2"},{"UserName":"User3","Avatar":"3"}]
at L1 of type org.json.JSONArray cannot be converted to JSONObject
Here's my code:
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = new JSONArray(jsonObject.getJSONObject("L1"));
ArrayList<Integer> arrList = new ArrayList<>();
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
arrList.add(json.getInt("Avatar"));
AvatarList = arrList;
}
}
String query_result = "SUCCESS";
if (query_result.equals("FAILURE")) {
} else {
setAvatars(AvatarList);
}
} catch (JSONException e) {
Log.e("log_tag", "Error converting result "+e.toString());
}
If I use
jsonObject.getJSONArray("L1")
I get the same error.
Any suggestions?
Thanks in advance!
(edit: I made a mistake in the original post. There was a missing curly brace in the JSON string. Thanks to those who caught that)
Try the below one.Its working fine. I'm using json-simple-1.1.1 jar
String r="{\"L1\":[{\"UserName\":\"User1\",\"Avatar\":\"1\"},{\"UserName\":\"User2\",\"Avatar\":\"2\"},{\"UserName\":\"User3\",\"Avatar\":\"3\"}],\"L2\":[{\"UserName\":\"User4\",\"Avatar\":\"4\"},{\"UserName\":\"User5\",\"Avatar\":\"5\"}]}";
Object obj=JSONValue.parse(r);
JSONObject jsonObject = (JSONObject) obj;
JSONArray jsonArray = (JSONArray) jsonObject.get("L1");
ArrayList<Integer> arrList = new ArrayList<>();
if (jsonArray != null) {
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject json = (JSONObject) jsonArray.get(i);
arrList.add((Integer.parseInt((String) json.get("Avatar"))));
AvatarList = arrList;
}
}
String query_result = "SUCCESS";
if (query_result.equals("FAILURE")) {
} else {
setAvatars(AvatarList);
}
This ended up working for me if anyone stumbles upon this. I don't really understand why this worked and my original method didn't... something to do with JSONObjects vs JSONArrays vs Strings and things like [, {, }, and ] probably.
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonArray = new JSONArray(jsonObject.getString("L1"));
ArrayList<Integer> arrList = new ArrayList<>();
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
arrList.add(json.getInt("Avatar"));
AvatarList = arrList;
}
}
I am trying to extract Key and values from my JSONObject. But i am not able to do that. Here is the JSON:
[{"id":["5"]},{"Tech":["Java"]}]
It is a String initially. I have converted that to JSONObject using :
JSONObject jsonObj = new JSONObject("[{"id":["5"]},{"Tech":["Java"]}]");
Then i am trying to get the key and value by:
jsonObj.getString("id");
But its giving me null. Can anyone help me out here?
Try this:
try {
JSONArray jsonArr = new JSONArray("[{\"id\":[\"5\"]},{\"Tech\":[\"Java\"]}]");
for (int i = 0; i < jsonArr.length(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
String k = jsonObj.keys().next();
Log.i("Info", "Key: " + k + ", value: " + jsonObj.getString(k));
}
} catch (JSONException ex) {
ex.printStackTrace();
}
Parameter you are sending is JsonArray and referring to JsonObject. The Correct way is
JSONObject jsonObj = new JSONObject("{'id':['5','6']},{'Tech':['Java']}");
System.out.println(jsonObj.getString("id"));
JSONArray jsonArray = new JSONArray("[{'id':['5','6','7','8']},{'Tech':['Java']}]");
System.out.println(jsonArray.length());
for(int i=0;i<jsonArray.length();i++){
System.out.println(jsonArray.getJSONObject(i).getString("id"));
}
Because at id you dont have a string , you have a array of string ,
so insted of doing this
jsonObj.getString("id");
do this
jsonObj.getArray("id"); this will give you that array in return
like if you have a Json Array at id then you have to do this
jsonObj.getJSONArray("id");
I have JSON from file.
{
"from_excel":[
{
"solution":"Fisrt",
"num":"1"
},
{
"solution":"Second",
"num":"2"
},
{
"solution":"third",
"num":"3"
},
{
"solution":"fourth",
"num":"4"
},
{
"solution":"fifth",
"num":"5"
}
]
}
and want to parse list of Solution and Num.
Used lib org.json.simple.*
Try this one
Object obj = parser.parse(new FileReader("E:\\json.txt"));
JSONObject jsonObject = (JSONObject) obj;
out.println(jsonObject.get("from_excel"));
JSONObject obj_new = (JSONObject) jsonObject.get("from_excel");
JSONArray solution = (JSONArray) obj_new.get("solution");
Iterator iterator = solution.iterator();
while (iterator.hasNext()) {
out.println(iterator.next());
}
What am I doing wrong?
If try to write
JSONObject solutions = (JSONArray) jsonObject.get("from_excel");
If try to write
JSONArray array = obj.getJSONArray("from_excel");
get error
working solution
JSONParser parser = new JSONParser();
JSONObject jsonObject;
try {
jsonObject = (JSONObject) parser.parse(new FileReader("E:\\json.txt"));
out.println("<br>"+jsonObject);
JSONArray from_excel = (JSONArray)jsonObject.get("from_excel");
// for row output 1
for(Object o: from_excel){
out.println("<br>"+o);
}
// for row output 2
Iterator iterator = from_excel.iterator();
while (iterator.hasNext()) {
out.println("<br>"+iterator.next());
}
// for item output 3
for (int i = 0; i < from_excel.size(); i++) {
JSONObject jsonObjectRow = (JSONObject) from_excel.get(i);
String num = (String) jsonObjectRow.get("num");
String solution = (String) jsonObjectRow.get("solution");
out.println("<br>num="+num+"; solution="+solution);
}
} catch (Exception e) {
out.println("Error: "+e);
}
There is no "solution" array in the JSON. "from_excel" is the array. So your code should look like this :
Object obj = parser.parse(new FileReader("E:\\json.txt"));
JSONObject jsonObject = (JSONObject) obj;
out.println(jsonObject.get("from_excel"));
JSONArray solutions = (JSONArray) jsonObject.get("from_excel");
Iterator iterator = solutions.iterator();
while (iterator.hasNext()) {
out.println(iterator.next());
}
from_excel is JSON array not an object. So you should achieve it is array.
JSONObject jsonObject = (JSONObject) obj;
JSONArray array = obj.getJSONArray("from_excel");
then iterate the array and get each jsonobject. Something like the below
for(int i = 0 ; i < array.length() ; i++){
array.getJSONObject(i).getString("solution");
}
How would you suggest me to parse this JSON:
{"17": {"user_name": "test1"}, "18": {"user_name": "test5"}, "19": {"user_name": "test9"}}
I need to get "username",but i cant find the way to do it. Maybe i should change JSON to something like that:
[{"user_name": "test1"},{"user_name": "test5"},{"user_name": "test9"}]
This way i tried to get "user_name"s:
try {
List<String> allNames = new ArrayList<String>();
String str = "[{"user_name": "test1"},{"user_name": "test5"},{"user_name": "test9"}]";
JSONObject json = new JSONObject(str);
for ( int i = 0; i < json.length() ; i++)
{
JSONObject actor = json.getJSONObject(i);
String user_name = actor.getString("user_name");
allNames.add(user_name);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But then i get Problem with that line:
JSONObject actor = json.getJSONObject(i);
Android studio tells me that JSONObject cannot be applied to int(i). I have no idea why it doesn't work.
Can somebody please give me some hint, tutorial or an example?
Much appreciated !
The method JSONObject.getJSONObject requires a String argument (the name or key of the object), not an int. In your case, the keys are "17", "18" and "19". To get all keys, use the JSONObject.keys() method:
JSONObject json = new JSONObject(str);
Iterator<String> keyIterator = json.keys();
while (keyIterator.hasNext()) {
JSONObject actor = json.getJSONObject(keyIterator.next());
String user_name = actor.getString("user_name");
allNames.add(user_name);
}
Android studio tells me that JSONObject cannot be applied to int(i)
Because JSONObject.getJSONObject method takes key name as String instead of int. and keys in posted json is 17,18,... to access inner JSONObject.
To get all user_name from JSONObject,need to get all keys:
Iterator<String> iter = json.keys();
while (iter.hasNext()) {
String key = iter.next();
JSONObject actor = json.getJSONObject(key);
String user_name = actor.getString("user_name");
allNames.add(user_name);
}
Change your code like this
try {
List<String> allNames = new ArrayList<String>();
String str = "[{"user_name": "test1"},{"user_name": "test5"},{"user_name": "test9"}]";
JSONOArray jsonArray = new JSONOArray(str);
for ( int i = 0; i < jsonArray .length() ; i++)
{
JSONObject actor = jsonArray.getJSONObject(i);
String user_name = actor.getString("user_name");
allNames.add(user_name);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if you use the Gson library it's very easy.
String json = "{\"17\": {\"user_name\": \"test1\"}, \"18\": {\"user_name\": \"test5\"}, \"19\": {\"user_name\": \"test9\"}}";
Gson gson = new GsonBuilder().create();
Map<String,User> users = gson.fromJson(json, new TypeToken<Map<String,User> >(){}.getType());
for(String key : users.keySet()) {
Log.d("DEBUG",key+" -> "+users.get(key).getUser_name());
}
The User class is a simple POJO like:
public class User {
private String user_name;
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
}
str = {"17": {"user_name": "test1"}, "18": {"user_name": "test5"}, "19": {"user_name": "test9"}}
JSONObject ob1 = new JSONObject(str)
JSONObject ob2 = ob1.getJSONObject("17");
String userName = ob2.getString("user_name");
str = [{"user_name": "test1"},{"user_name": "test5"},{"user_name": "test9"}]
List<String> allNames = new ArrayList<String>();
JSONArray jsonArray = new JSONArray("str");
for(i=0; i < jsonArray.length(); i++){
JSONObject ob = jsonArray.getJSONObject(i);
allNames.add(ob.getString("user_name")
}
you are trying to parse JSONArray into JSONObject at
JSONObject json = new JSONObject(str);
use the below code.....
try {
List<String> allNames = new ArrayList<String>();
String str = "[{"user_name": "test1"},{"user_name": "test5"},{"user_name": "test9"}]";
JSONArray json = new JSONArray(str);
for ( int i = 0; i < json.length() ; i++)
{
JSONObject actor = json.getJSONObject(i);
String user_name = actor.getString("user_name");
allNames.add(user_name);
}
} catch (JSONException e) {
// TODO Auto-generated catch block`enter code here`
e.printStackTrace();
}
I have a webservice which returns a JSON array in this format:
[{"imageid":"3","userid":"1","imagepath":"SLDFJNDSKJFN","filterid":"1","dateadded":"2014-05-06 21:20:18.920257","public":"t"},
{"imageid":"4","userid":"1","imagepath":"dsfkjsdkfjnkjdfsn","filterid":"1","dateadded":"2014-05-06 21:43:37.642748","public":"t"}]
I need to get all the attributes seperately? How would I do this?
I know how to do it with JSONObject if there is just 1 thing being returned, but how does it work when multiple items are returned?
Thanks
try {
JSONArray jArray = new JSONArray(jsonString);
String s = new String();
for (int i = 0; i < jArray.length(); i++) {
s = jArray.getJSONObject(i).getString("imageid").toString();
s = jArray.getJSONObject(i).getString("userid").toString();
}
} catch (JSONException je) {
}
Create an Object class with all variables, create a List for this Object, add all objects in your JSONArray to the list, use the one you need.
List<YourObject> objList = new ArrayList<YourObject>();
JSONArray a = new JSONArray(response);
int size = a.length();
for (int i=0 ; i<size ; i++){
JSONObject aa = a.getJSONObject(i);
String id = aa.getString("imageid");
String userid = aa.getString("userid");
String imagepath = aa.getString("imagepath");
String filterid = aa.getString("filterid");
String dateadded = aa.getString("dateadded");
String publicText = aa.getString("public");
YourObject obj = new YourObject(id,userid,imagepath,filterid,dateadded,publicText);
objList.add(obj);
}
So what you are having here is some JSON objects inside a JSON array.
What you want to do is this:
JSONArray array = ...;
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
// Extract whatever you want from the JSON object.
}
I hope it helped.
You can use JSONArray to parse array of JSON response.
private void parseJsonArray(String response) {
try {
JSONArray array = new JSONArray(response);
for(int i=0;i<array.length();i++){
JSONObject jsonObject = array.getJSONObject(i);
String ImageId = jsonObject.getString("imageid");
Log.v("JSON Parser", "ImageId: "+ImageId);
}
} catch (Exception e) {
e.printStackTrace();
}
}