I have a nested JSON object and I want to access 3 values from it which is the best-optimized way to call it.
'''
item.put(ITEM_COUNT, order.getJSONObject("name").getString("key1"));
item.put(PRICE, order.getJSONObject("name").getLong("key2"));
item.put(ITEM_NAME,order.getJSONObject("name").getJSONObject("key3").getString("key4"));
'''
or I need to create a JSON object name and the i have to get each value like
JSONObject name = order.getJSONObject("name"); and use this object now
Related
In the example
If the json object has a missing value for 'age',
String source = "{
name : John;
age : ;
score: 100
}"
here the json might be in wrong format, I am not sure about this. And I want to ignore those keys which don't have values.
JSONObject object = objectMapper.readValue(source, JSONObject.class);
Error getting:
com.fasterxml.jackson.databind.RuntimeJsonMappingException: Instantiation of [simple type, class org.json.JSONObject] value failed: Missing value at [some line number] (through reference chain: com.bial.rs.model)
Note : JSONObject is from org.json package
If you want to avoid NullPointerException you better make use of optString() method to extract the values from JSON
If you are fetching the data from JSON at any time, you might have null data for a particular Key value, at that time instead of implementing Null conditions, better make use of this optimized method optString("age") it will return null and does not throw JSONException
I have previously used GSON, which automatically transfers the data as long as my custom object has a variable with the same name. However, this time, I'm also intrested in the name, or ID, of the object. The object only contains a single long. Example of how it looks:
{"1":123,
"2":124,
"4":125,
"5":126,
"6":127}
As you can see, the list don't necessarily contain all sequent IDs so I cannot just create a list. How would you solve the problem?
Instead of deserializing to a specific custom object, just deserialize to Map<String, Integer>:
Type type = new TypeToken<Map<String, Integer>>(){}.getType();
Map<String, Integer> result = gson.fromJson(jsonString, type);
Use jython:
import json
json_data = json.loads(your_string_above)
ids = json_data.keys()
# ids now contains [u'1', u'2', u'4', u'5', u'6']
Hope that helps.
How to pass payload/ Form parameters making as JSON object with some strings are like "User[user]", while using the Restemplate?
In my project i have a complex json response. I want to read it by GSon.
JSON : {'FoodMenuRS':{'Results':[{'Items':{'Item':[{'#Id':'24'},{'#Id':'24'}]}}, {'Items':{'Item':{'#Id':'24'}}}]}}
It contains a JSONArray with first "Item" and JSONObject with second one. Hence its call results in error,
failed to deserialize json object {"#Id":"24"} given the type java.util.List<com.servlet.action.ItemInfo> and java.lang.IllegalStateException: This is not a JSON Array.
Please help how i should handle this scenario. Thanks.
The string you are showing is a JSONObject not a JSONArray. So, in this case you first of all have to get the JSONObject and perform further decoding on that JSONObject.
JSONObject - {}
JSONArray - []
And indeed JSONObject or JSONArray should be encoded using Double-quotes(")
Your JSON is valid, but not for the doble quotes (") because JSON supports simple quotes (') and no quotes in the key name. See http://sites.google.com/site/gson/gson-user-guide#TOC-Serializing-and-Deserializing-Colle
However this JSON have key names that begin with #. For JSON strings this character is valid at the beginning of the name (see right column http://www.json.org/) but for Java this names are illegal (see Naming section http://download.oracle.com/javase/tutorial/java/nutsandbolts/variables.html). Specifically, names started with # are annotations and you can't use annotations tags to declare variables, fields, methods, etc.
This is not a valid JSON object. Strings in JSON are always encapsulated in double quotes ("). Contact the producer of that JSON and tell him to use a correct encoder.
If a have a Java object (lets say a User object), and I use velocity to template the page
so I can access a field in the user object like ${user.id}, is there an easy way to convert this into a javascript object (so I can access the fields of the User object)?
I can assign a value to javascript variable like
var id = "${user.id}";
but if i do
var user = "${user}";
this isn't true:
id == user.id;
And I would rather not have to do
var user = { id: "${user.id}" ...}
Maybe you should transform your user object to a JSON.
You can create a utility method that uses reflection and gets each attribute from an object and put in a String. Maybe you can create an annotation to mark which attributes should be included in the JSON.
This way you send to your template something like this
"{id: '1', name:'stevebot'}"
And in you velocity file
var user = ${user};