This question already has answers here:
How can I turn a JSONArray into a JSONObject?
(4 answers)
Closed 4 years ago.
I am writing a rest java service. I want to convert my JSONArray to JSONObject and return it. But I am getting "{}" as output when I hit my rest service from browser. Although it is printing fine inside rest service when i tried to print using System.out.println();
PreparedStatement dimDelPS = null;
ResultSet dimDelRS = null;
dimDelPS = connection.prepareStatement("select * from abc");
dimDelRS = dimDelPS.executeQuery();
String dimLow=null;
while (dimDelRS.next()) {
int total_rows = dimDelRS.getMetaData().getColumnCount();
for (int i = 0; i < total_rows; i++) {
org.json.JSONObject obj = new org.json.JSONObject();
obj.put(dimDelRS.getMetaData().getColumnLabel(i + 1)
.toLowerCase(), dimDelRS.getObject(i + 1));
jsonArray.put(obj);
}
}
System.out.println("json1 :"+jsonArray);
//Sample output at this stage: ["{\"employee\":\"ANTHONY.DUNNE\"}","{\"type\":\"Manager\"}"]
dimDelRS.close();
dimDelPS.close();
JSONObject jsobobject= new JSONObject();
jsobobject.put("aoColumnDefs",jsonArray);
System.out.println(jsobobject);
return jsobobject;
You can't just return JSONObject.
You need to male sure you Marshall it into json.
'return Response.ok(jsonObject.toString(), MediaType.APPLICATION_JSON).build();'
Browser understand String, and not java object.
Related
This question already has answers here:
How to parse JSON array from file?
(3 answers)
Closed 5 years ago.
I´ve been trying to parse this Json format but since it has no name for the array i have no idea how to parse it... Thanks for your help and time.
Im using JSON simple library as a parser.
[
{
"Name":"John",
"LastName":"Wick"
},
{
"Name":"Johny",
"LastName":"Wicked"
}
]
the code im trying to use is this one :
JSONArray jsonarray = new JSONArray("data/names.json");
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
String name = jsonobject.getString("name");
String url = jsonobject.getString("url");
}
You can use Jackson built in tree model. For example like this
ObjectMapper mapper = new ObjectMapper();
JsonNode rootArray = mapper.readTree(new File("c:\\jsonfile.json"));
for(JsonNode root : rootArray) {
// your code
...
}
This question already has answers here:
how to check if a JSONArray is empty in java?
(4 answers)
Closed 5 years ago.
my json string is
String RESPONSE = " { "Table": [] } ";
and I use
JSONObject jsonObj = new JSONObject(RESPONSE);
JSONArray contacts = jsonObj.getJSONArray("Table");
Therefore, contacts = [] I mean empty.
How can I control that array is empty.
After this controller I use this command
JSONObject c = contacts.getJSONObject(0);
Of course is not empty :)
You can use length function:
JSONObject jsonObj = new JSONObject(RESPONSE);
JSONArray contacts = jsonObj.getJSONArray("Table");
if(contacts.length() > 0 ) {
JSONObject c = contacts.getJSONObject(0);
}
You could use the isNull() function.
JSONObject jsonObj = new JSONObject(RESPONSE);
JSONArray contacts = jsonObj.getJSONArray("Table");
if(!contacts.isNull(0)) {
JSONObject c = contacts.getJSONObject(0);
}
This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 7 years ago.
String response = "{\"mon\" : [[16,20]],\"sun\":[[10,20]]}";
Basically, how do I get one object of 2 items where in each item is an int array of 2 elements. Sample code please.
JSONArray jsonArray = jsonObject.getJSONArray("mon");
JSONArray weekdayArray = jsonArray.getJSONArray(0);
int size = weekdayArray.length();
String weekday[] = new String[size];
int[] wday = new int[size];
for(int i=0; i < size ; i++) {
weekday[i] = weekdayArray.getString(i);
wday[i] = Integer.parseInt(weekday[i]);
}
Where you get this json? because this json format is incorrect,if you necessary validate this json , access the http://json.parser.online.fr/ e paste your json e verify if this json is correct.
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");
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
}