accessing keys/values in JSONObject in java - java

In java I have the following code:
import org.json.JSONObject;
JSONObject obj = new JSONObject();
obj.put("firstKey", new JSONObject());
Now in the new object corresponding to the key "firstKey", I want to start inserting new key-value pairs, but I'm not sure how to do this. I've tried oppJSON.get("firstKey").put("one","two"); but this doesn't work - does anyone have any ideas?

JSONObject have specific get methods like getString, getInt, getDouble etc. In your case, you need getJSONObject
oppJSON.getJSONObject("firstKey").put("one","two");

Class JSONObject implements a Map without generics. So while you can use Map<String, String>, JSONObject is the equivalent of Map<Object, Object>. Everything pulled out of it using get has to be cast to its type.
Try ((JSONObject)obj.get("firstKey")).put("one", "two")

Related

I am trying to merge two JsonObjects in java

I have JsonObjects fields,obj2.I am trying to add fields in both the objects.
JsonObject fields=commonfields.getJsonObject("fields");
JsonObjet additional=jo.getJsonObject("zas");
fields.put(additional);
Expected outcome should be merged fields of two objects.I am getting errors.
For io.vertx.core.json.JsonObject, you can use mergeIn method.
JsonObject fields = new JsonObject();
fields.putString("a", "1");
fields.putBoolean("b", false);
JsonObject additional = new JsonObject();
additional.putString("c", "1");
additional.putBoolean("d", false);
fields.mergeIn(additional);
System.out.println(fields);`
javax.json.JsonObject provides putAll method, as it implements Map interface.
For other types of JsonObject, which do not implements Map interface you can parse over keys and explicitly put key, value pair in JsonObject.

How to convert Json string with key-value pair into string with only value

I actually converted my pojo data into json string this way,
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
String json=gson.toJson(user);
I got the json string but that is not the format i actually need, i got
json = {"userID":300,"userName":"asd","password":"s","enabled":1}
So, I want to convert Json string with key-value pair as below ,
{"userID":300,"userName":"asd","password":"s","enabled":1}
into Json string with only value (without key) as below
[300,"asd","s",1]
So I continue after your string json.
// lets deserialize your json string and get a hashmap
Type collectionType = new TypeToken<HashMap<String, Object>>(){}.getType();
HashMap<String, Object> hm = gson.fromJson(json, collectionType);
String finalJson = gson.toJson(hm.values());
// aand taa-daa!!
System.out.println(finalJson);
now finalJson is [300,"asd","s",1]
Edit: libraries are as following:
import java.lang.reflect.Type;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
You could whack the properties of the user into a List<Object> and then JSON that.
This would mean GSON made an JSON array out of the List and you would get what you want.
As this doesn't seem to make much sense as a use case you would have to do a bit of hardcoding - I don't think GSON can do this for you:
final List<Object> props = new LinkedList<>();
props.add(user.getId());
props.add(user.getUserName());
//etc
final String json=gson.toJson(props);
Could I ask why do you want to do that? If you retrieve that Json without key-value how you will know, for example, that 300 is his id and not his money property?
You can't difference between your properties and I don't really recommend it.
Anyway, the only way I find to do that, is to "break" your string manually, replacing your properties with blank values, like json.replace("\"userID\"", ""); and you should do it for every property.

Can't parse JSON array of arrays to LinkedHashMap in Jackson

I' m developing an Android REST client. We use JSON as data exchange format, so I use a Jackson parser. I get different Json responses from the server like simple arrays:
{"user_id":"332","user_role":"1"}
or something else. All these stuff I parse to LinkedHashMap<String, Object> and everything works perfectly but when I got this response from the server:
[ { "user_id":"352",
"user_role":"expert",
"name":"Test 12-18",
"description":"Test" },
{ "user_id":"263",
"user_role":"novice lab",
"name":"Tom's Desk",
"description":"Desk"}
]
I got null: {} after parsing.Here is my code where i use Jackson:
ObjectMapper mapParametersToJSON = new ObjectMapper();
String serverResponseBody = responseFromServer.getBody();
LinkedHashMap<String, Object> resultofOperation = new LinkedHashMap<String,
Object>();
TypeReference<LinkedHashMap<String,Object>> genericTypeReferenceInformation = new
TypeReference<LinkedHashMap<String,Object>>() {};
try {
resultofOperation = mapParametersToJSON.readValue(serverResponseBody,
genericTypeReferenceInformation);
So, why Jackson failed to parse this? How can I fix this?
Others have suggested the problem, but solutions are bit incomplete. If you need to deal with JSON Objects and Arrays, you can either bind to java.lang.Object, check the type:
Object stuff = objectMapper.readValue(json, Object.class);
and you will get either List or Map (specifically, ArrayList or LinkedHashMap, by default; these defaults can be changed).
Or you can do JSON trees with JsonNode:
JsonNode root = objectMapper.readTree(json);
if (root.isObject()) { // JSON Object
} else if (root.isArray()) { ...
}
latter is often more convenient.
One nice thing is that you can still create regular POJOs out of these, for example:
if (root.isObject()) {
MyObject ob = objectMapper.treeToValue(MyObject.class);
}
// or with Object, use objectMapper.convertValue(ob, MyObject.class)
so you can even have different handling for different types; go back and forth different representations.
The first JSON in your question is a map, or an object. The second is an array. You're not parsing an array, you're parsing a map.
You need to do something like this:
List<MyClass> myObjects = mapper.readValue(jsonInput, new TypeReference<List<MyClass>>(){});
Almost identical question with answer here.
In JSON the {"key": "value"} is Object and the ["this", "that"] is Array.
So, in case when you're receiving the array of objects you should use something like List<Map<Key, Value>>.
You are facing an error, because [] construction can't be translated into Map reference, only in List or array.
I would recommend do it something in this way:
ObjectMapper objectMapper = new ObjectMapper();
List<Map<String,String>> parsedResult = objectMapper.reader(CollectionType.construct(LinkedList.class, MapType.construct(LinkedHashMap.class, SimpleType.construct(String.class), SimpleType.construct(String.class)))).readValue(serverResponseBody);
//if you need the one result map
Map<String, String> resultMap = new LinkedHashMap<String, String>();
for (Map<String, String> map: parsedResult){
resultMap.putAll(map);
}

JSONObject.append into object - result is nested array?

Following code produces a nested array as a result for keys containing three items:
import org.codehaus.jettison.json.JSONObject;
// ...
JSONObject ret = new JSONObject();
for (Key key:keys) ret.append("blocked",key.id());
The result is:
{"blocked": [[["1"],"2"],"3"]}
Is this expected? If it is, how can I construct a plain array adding item by item?
You need to create a JSONArray object:
JSONObject ret = new JSONObject();
JSONArray arr = new JSONArray();
arr.put("1");
arr.put("2");
arr.put("3");
ret.put("blocked", arr);
The result is:
{"blocked":["1","2","3"]}
It's curious because the API says the following:
Append values to the array under a key. If the key does not exist in the
JSONObject, then the key is put in the JSONObject with its value being a
JSONArray containing the value parameter. If the key was already
associated with a JSONArray, then the value parameter is appended to it.
But it doesn't work correctly. When I do:
JSONObject o = new JSONObject();
o.append("arr", "123");
o.append("arr", "456");
I get an Exception saying that "JSONObject[arr] is not a JSONArray". It looks like there is a bug.
I ran into a similar problem. You should use the put method; not the append method. And, of course, you should create a JSONArrray and use that as the second argument of the put method.

put method in the json object adds value to the first of the jsonobject;

Consider following piece of code:
JSONObject json = new JSONObject();
json.put("one", 1);
json.put("two", 2);
json.put("three", 3);
If i print the jsonobject it prints like this
{"three":"1","two":"2","one":"1"}
But i want like this.
{"one":"1","two":"2","three":"3"}
Please help. Thanks in advance.
The documentation at http://www.json.org/javadoc/org/json/JSONObject.html says:
A JSONObject is an unordered collection of name/value pairs.
In other words, properties of an object are accessed by name, not by position and the default serialized form does not guarantee any specific order.
Strict positioning comes only with arrays:
JSONArray json = new JSONArray();
json.put("1");
json.put("2");
json.put("3");
json.toString(); // results in ["1", "2", "3"]
The easiest workaround to solve your problem is to use the sortedKeys() method and by iterating the JSONObject key by key, produce the JSON string manually in what ever order necessary. Implementing a custom Comparator might help also.

Categories