JSONArray constructor issue - java

{"balance":1000.21,"is_vip":true,"num":100,"name":"foo"}
This is my json string. I want to iterate each element and get my output as
1000
true
100
foo
I tried creating JSONArray with the following syntax
JSONArray jsonarr = new JSONArray(myString);
But the error thrown is
"The constructor JSONArray(String) is undefined"
So what can be the possible solution this?

You have to use JSONObject class instead:
JSONObject jso = new JSONObject(yourJsonString);
// values
for(int i = 0; i<jso.names().length(); i++){
System.out.println( jso.get( jso.names().getString(i) ) );
}

Related

I have a json object. I want to access in java service. I am trying to parse it

I am using import net.sf.json.JSONObject
My object is like this:
[{
"courseId": "AUTO_CAD",
"strDate": "02-04-2012"
}, {
"courseId": "CNC_PROG",
"strDate": "03-04-2012"
}]
Please help me how to access this in java service
//The code that i have tried.
List<JSONObject> jsonList = new ArrayList<JSONObject>();
jsonList = (List<JSONObject>) context.get("courseData"); // courseDate is my json object
JSONObject obj = jsonList.get(0);
Debug.log("courseStartDate ="+ obj.getJSONObject("courseId"));
//Using this gives me the following error. org.ofbiz.webapp.event.EventHandlerException: Service invocation error (java.lang.String cannot be cast to net.sf.json.JSONObject)
Have not tested yet the code, but worth a try:
JSONArray courses = new JSONArray(json);
JSONObject first = courses.getJSONObject(0); //Or access in a loop using courses.length()
Debug.log("CourseID: "+ first.getString("courseId"));
You can do this:
JSONObject json = (JSONObject) JSONSerializer.toJSON(jsonTxt);
System.out.println(pilot.getString("aKey"));
Here you have an ArrayList yourObject
for (int i = 0; i < yourObject.size(); i++) {
System.out.println(yourObject.get(i).getCourseId());
System.out.println(yourObject.get(i).getStrDate());
}

Error when using JSONSimple to write a json file with for loop

I need to transform my data in a ArrayList to a JSON file, and I use JSON.simple. Everything is fine except one little thing that I want to get a result like ...... {source:0, target:1},{source:0, target:1},{source:0, target:2},{source:0, target:3} ...... but it returns ......{source:0, target:16},{source:0, target:16},{source:0, target:16}...... . My solution.size() is 17.
Here is my code:
JSONObject jsonObject = new JSONObject();
JSONObject jsonNodesObject = new JSONObject();
JSONObject jsonEdgesObject = new JSONObject();
JSONArray jsonNodesArray = new JSONArray();
JSONArray jsonEdgesArray = new JSONArray();
String instString = solutions.get(0).get("institution");
jsonNodesObject.put("name", instString);
// extract name and institution from ArrayList
for (int i = 0; i < solutions.size(); i++)
{
HashMap<String, String> eleHashMap= solutions.get(i);
String nameString = eleHashMap.get("name");
jsonNodesObject.put("name", nameString);
jsonNodesArray.add(jsonNodesObject);
jsonEdgesObject.put("source", 0);
jsonEdgesObject.put("target", i);
jsonEdgesArray.add(jsonEdgesObject);
}
jsonObject.put("nodes", jsonNodesArray);
jsonObject.put("edges", jsonEdgesArray);
System.out.println(jsonObject);
It seems that in every for loop, it refreshes the value of target: i of all my jsonEdgesArray.
Dose anyone know how to fix this? Thanks in advance!
As your iterating jsonNodesObject in for loop, same value will be put for jsonNodesObject.put("name", nameString); u have to initialize JSONObject jsonNodesObject = new JSONObject(); inside for loop

Mapping JSON to arrays/objects in Java - Android

I have a web system that returns a json string with the data that I need in an Android App. The string is below:
[
{"id":1,
"title":"Remove ViRuSeS",
"tagline":"Remove ViRuSeS",
"body":"Body",
"image":"index.jpg",
"steps":[
{"id":2,
"title":"Step 1",
"body":"Download Things!",
"position":1}
]
}
]
It should return an array of objects, with one of the object's items also being an array of items.
I am familiar with gson and have gotten this working in the past, but I always had to simplify my data down to just an object, which makes me end up have to make multiple calls to get the data.
Is there a good way to do this without having to map all of the possible values back into classes?
My last attempt was to just try to get something simple out of this and am getting a NullPointerException on the second of these lines:
userDet = new JSONObject(string);
JSONArray userDetJson = userDet.getJSONArray("Steps");
change it to "steps" and not "Steps" , It will fix it:
userDet = new JSONObject(string);
JSONArray userDetJson = userDet.getJSONArray("steps");
The full parsing method:
JSONArray mainArray = new JSONArray(json);
for (int i = 0 ; i < mainArray.length() ; i ++)
{
JSONObject currentItem = array.getJSONObject(i);
String title = currentItem.getString("title");
String body = currentItem.getString("body ");
....
JSONArray currentItemStepsArray = currentItem.getJSONArray("steps");
for (int j = 0 ; j < currentItemStepsArray.length() ; j ++)
{
....
}
}
Here, try this:
JSONArray topLevelArr = new JSONArray(json);
JSONArray stepArr = topLevelArr.getJSONObject(0).getJSONArray("steps");

Issue With JSON Object in Java?

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

Json Array not properly generated

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
}

Categories