How to nest objects when building JSON with JSONObject - java

I'm trying to encode this string for a POST request. Can anyone tell me how I can encode
{"jsonrpc": "2.0", "method": "Files.GetSources", "params":{"media":"music"}, "id": 1}
So far I have
JSONOjbect obj = new JSONObject();
obj.put("jsonrpc", "2.0");
obj.put("method", "Files.GetSources");
But I'm not sure how to put in the rest - can anyone help?

If you're asking how you'd put the nested params object in there, you'd probably do:
JSONObject params = new JSONObject();
params.put("media", "music");
obj.put("params", params);
To use an array (per your comments below), you'd do something like this:
JSONArray properties = new JSONArray();
properties.put("resume");
properties.put("genre");
properties.put("studio");
...
JSONObject params = new JSONObject();
params.put("properties", properties);
obj.put("params", params);

JSONOjbect obj = new JSONObject().put("jsonrpc", "2.0")
.put("method", "Files.GetSources").put("id", 1)
.put("params", new JSONObject().put("media", "music"));
Chaining .put() like this is possible because put() returns the object it was called on - for this exact purpose.

You have two choices. You can create another object that holds "media":"music" and then put that in the original JSONObject or you can just pass this whole string into the JSONObject constructor and have it parse it for you.

Well, if you do have the string before hand, you can simply do
JSONObject object = JSONObject.getJSONObject("{\"jsonrpc\": \"2.0\", \"method\": \"Files.GetSources\", \"params\":{\"media\":\"music\"}, \"id\": 1}");

Related

How to set array value in the jsonobject

I am getting the array values as
I need to construct the object as jsonObject.
So I have added like below but the returning object as an error.
How can I add the array as expected in the users.
Note: Here I am sending the users in array from a fragment to set the values in my payload
private String mUserArray; //value =["user1", "user2"]
mUserArray is added in the constructor.
final JsonArray array = new JsonArray();
array.add(mUserArray1);
final JsonObject jo = new JsonObject();
jo.addProperty("type", "value")
jo.add("usernames" , array); // If i set the userarray it failed to convert Added like this as well//new JsonPrimitive(mUserArray1)
return jo;
Expected Result:
{"type": "value", "usernames":["user1", "user2"]}
Actual Result:
{"type":"value","usernames":"[\"user1\", \"user2\"]"}
It seems like that you added the usernames property as a string literal rather than as a JSON array. You can construct a JsonArray of strings from a Java array the following way.
String[] userArray = {"user1", "user2"};
JsonArray userJsonArray = new JsonArray();
for(String user: userArray){
userJsonArray.add(new JsonPrimitive(user));
}
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("type", "value");
jsonObject.add("usernames", userJsonArray);
Note that JsonObject::addProperty only adds primitives to the JSON object rather than arrays or objects.

Value as string array in gson key value

I'm new to JSON. I'm trying to assign value (in key value pairs) as array of strings using GSON.
The JSON should look like as below:
{ "name": "path", "value": [ "/my-path" ,"/my-path2","/newpath"] }
How can I achieve this?
Thanks.
Even thoe I will hardly recommend you to use POJOS, gson is flexible enough to allow you to do what you want:
JsonObject jo = new JsonObject();
jo.addProperty("name", "path");
JsonArray jsonArray = new JsonArray();
jsonArray.add("my-path");
jsonArray.add("my-path2");
jsonArray.add("my-new-path");
jo.add("value", jsonArray);
System.out.println(jo);

JSONObject not workign

I am building an app for android.
I fire and HTTP GET request and this request returns a JSONObject. I want to retrieve the value by key. But this is not working properly.
This is the JSONObject named obj that I receive:
{"id":1,"name":"math","description":"This is a math course."}
If I log Log.d("title", String.valueOf(obj.has("name"))); this will result into true.
This works for all keys in the JSONObject.
But if I want to receive the name and do this so:
Log.d("title", obj.getString("name"));
I will get an unhandled exception: org.json.JSONException.
Does anybody know how I can fix this problem?
Maybe you should try someting like this:
Log.d("title", obj.name);
var obj = $.parseJSON('{"id":1,"name":"math","description":"This is a math course."}');
alert(obj['name']);
Try this :) You can use JSON.parse insted of $.parseJSON if you are not using jquery. Following in Java
String s = "{menu:{\"1\":\"sql\", \"2\":\"android\", \"3\":\"mvc\"}}";
JSONObject jObject = new JSONObject(s);
JSONObject menu = jObject.getJSONObject("menu");
Map<String,String> map = new HashMap<String,String>();
Iterator iter = menu.keys();
while(iter.hasNext()){
String key = (String)iter.next();
String value = menu.getString(key);
map.put(key,value);
}
Everything between the { } makes part of an array, so you first need to get a JSONArray like this:
JSONArray myJSONArray = obj.getJSONArray();
And then you can access the field values with:
myJSONArray.getString("name") etc...
Search on google how to work with JSONArray.

How to access nested objects of a Json File

the string I have into "jsonString" is the content of this link: http://85.18.173.82/cineca/wp5/json/events.json
Now I want the value "Day" of the second "Event".
JSONObject o = new JSONObject(jsonString);
String day = o.getString("XXXXXXXXXX");
System.out.println(day);
What does I have to put as argument of o.getString?
Many thanks
JSONObject obj = new JSONObject(json);
JSONArray array = obj.getJSONArray("Events");
for(int i = 0 ; i < array.length() ; i++){
System.out.println(array.getJSONObject(i).getJSONObject("Event").getString("Day"));
}
In this way, you can access, thanks.
The way you're constructing your JSONObject is wrong. By using this constructor you're not reading the json from that URL, you're actually using that string as a json representation (which it is not).
If you want to first read the json from your URL you'll have to do an HTTP GET request and then construct a JSONObject out of the response.
For more info, take a look at JSONObject docs

Is JSON same with GSON?

I have tried to run following code
Gson gson = new Gson();
String json = gson.toJson(result);
JSONObject jsonResponse = new JSONObject();
jsonResponse.put("sEcho", echo);
jsonResponse.put("iTotalRecords", iTotalRecords);
jsonResponse.put("iTotalDisplayRecords", iFilteredTotalRecords);
jsonResponse.put("aaData", json);
jsonResponse.toString();
JSONArray data = new JSONArray();
for (Object obj : result) {
JSONArray row = new JSONArray();
User user = (User) obj;
row.put(user.getId()).put(user.getUserName()).put(user.isEnabled());
data.put(row);
}
JSONObject jsonResponse2 = new JSONObject();
jsonResponse2.put("sEcho", echo);
jsonResponse2.put("iTotalRecords", iTotalRecords);
jsonResponse2.put("iTotalDisplayRecords", iFilteredTotalRecords);
jsonResponse2.put("aaData", data);
jsonResponse2.toString();
The result from toString function for both jsonResponse are as follows:
{"iTotalDisplayRecords":11,"iTotalRecords":11,"aaData":"[{\"creationTime\":0,\"enabled\":true,\"id\":1,\"loginDuration\":0,\"online\":false,\"password\":\"asda\",\"userName\":\"abiieez\"}]","sEcho":"1"}
{"iTotalDisplayRecords":11,"iTotalRecords":11,"aaData":[[1,"abiieez",true]],"sEcho":"1"}
I would like to eliminate the " symbol before [ and after ] from the first json response just like the second one (I noticed that the " is added after the array being put to the jsonResponse object). How can I accomplish this ?
Since you first convert your "result" to a String, and then add it to aaData, it will end up quoted, like a String should. If all you'd like to do is to remove the quotes, you could do something like this in line 2:
String json = "##" + gson.toJson(result) + "##";
and this in line 8:
jsonResponse.toString().replace("\"##", "").replace("##\"","");
(of course you need to choose the "quote marker" ## such that it will never appear as actual string content in your data anywhere else)
But the cleaner solution (although probably slower) would likely be to convert your String to an actual JSONObject by changing line 2 to:
JSONObject json = new JSONObject(gson.toJson(result));

Categories

Resources