Mapping JSON with varying object name - java

I'm quite new to JSON, and I've looked around trying to work out what to do but not sure if I fully understand. I am making an external API call returning:
2015-12-21 01:22:09 INFO RiotURLSender:60 - Total json:
{"USERNAME":{"profileIconId":984,"revisionDate":1450655430000,"name":"USERNAME2","id":38584682,"summonerLevel":30}}
Where 'USERNAME' (And USERNAME2 - which can be very slightly different to USERNAME) will vary depending on what you pass the call's parameters. I was using Jackson Object Mapper to map the individual values within the USERNAME object - but didn't realise I had to map the object as well.
I've been using annotations in the DTOs like:
#JsonProperty("profileIconId")
private Long profileIconId;
and mapping using:
summonerRankedInfoDTO = mapper.readValue(jsonString, SummonerRankedInfoDTO.class);
How do I map using a value of USERNAME which is changing every single time?
Also this seems a bit odd, is this bad practice to have the actual varying key rather than just have the same key and different value?
Thanks

you can use following mentioned annotation #JsonAnyGetter And #JsonAnySetter.
Add this code into ur domain class. So any non-mapped attribute will get populated into "nonMappedAttributes" map while serializing and deserializing the Object.
#JsonIgnore
protected Map<String, Object> nonMappedAttributes;
#JsonAnyGetter
public Map<String, Object> getNonMappedAttributes() {
return nonMappedAttributes;
}
#JsonAnySetter
public void setNonMappedAttributes(String key, Object value) {
if (nonMappedAttributes == null) {
nonMappedAttributes = new HashMap<String, Object>();
}
if (key != null) {
if (value != null) {
nonMappedAttributes.put(key, value);
} else {
nonMappedAttributes.remove(key);
}
}
}

You should try to keep the keys the exact same if possible and change values, otherwise you'll have to change your JSON. Since JSON returns a value from the key, the value can change to anything it wants, but you'll be able to return it from the key. This doesn't work the other way around though.
Anyway to your question, you may have a little better luck using something like the GSON library, its pretty simple to use.
You can create the instance and pass it the JSON string:
Gson gson = new Gson();
JsonObject obj = gson.fromJson(JSON_DOCUMENT, JsonObject.class);
Then you can get certain elements from that now parsed JSON object.
For example, in your JSON string, username returns another JSON element, so you can do:
JsonObject username = obj.get("USERNAME").getAsJsonObject();
Then just repeat the same steps from there to get whatever value you need.
So to get the name which returns "USERNAME2":
username.get("name").getAsString();
Coming together with:
JsonObject obj = gson.fromJson(JSON_DOCUMENT, JsonObject.class);
JsonObject username = obj.get("USERNAME").getAsJsonObject();
username.get("name").getAsString();

Related

Deserializing JSON using RestTemplate which can have changing key

I'm currently calling this API https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api#1/latest/currencies/gbp.json
This has the path param of gbp which then is included in the response
{
"date": "2021-09-14",
"gbp": {
// omitted for brevity
}
}
Im using the RestTemplate.getForObject method to make the GET HTTP request which is successful however i am not sure how i would go about typing the response.
I will be calling this url with multiple different path parameters. So for example https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api#1/latest/currencies/eur.json is valid which will result in a response of
{
"date": "2021-09-14",
"eur": {
// omitted for brevity
}
}
So its not as easy as typing a gbp property on the response as Map<String, Double> etc. And i dont want to create a different class for each possible response.
So my question basically is. How can i type this? I've tried to use a custom #JsonDeserialzer annotation on a class which represents the data however since it does not know the key that was a bit of a dead end.
Is the only way to achieve this by using a custom ObjectMapper where i can pass the key to a customer deserializer rather than using the annotation?
First, consider using WebClient instead of RestTemplate, if you're on spring framework 5 (or switch to the webflux stack).
You don't need a custom ObjectMapper, but can just loop the properties by using restTemplate.getForEntity, like:
ResponseEntity<String> response = restTemplate.getForEntity
ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(response.getBody());
Iterator<Map.Entry<String, JsonNode>> it = root.fields();
while (it.hasNext()) {
Map.Entry<String, JsonNode> field = it.next();
System.out.println("key: " + field.getKey());
//Add some logic here ;)
//Probably you want the second property, if it exists ...
if (it.hasNext) {
field = it.next();
JsonNode currencyNode = field.getValue();
}
}
If you need or want an object, try the #JsonAnySetter - see fe. here Unstable behavior with Jackson Json and #JsonAnySetter

How to receive customized JSON Object in Spring boot Api post Method

I am trying to receive a JSON object in #RequestBody which is not known to me i.e. the JSON Object could be of any length and data.
Let's say, JSON could be as shown below
{'seqNo': 10 }
{'country': 'US', 'state': 'CA'}
{'customer': 'Alex', product: 'UPS', date:'25-Mar-2018'}
And In Spring Boot Api, I have a method to receive that JSON Object.
#PostMapping(value = "/lookup")
public ResponseEntity<AppResponse> getLookup(#RequestBody LookupRequestObject lookupRequestObject) {
// THIS METHOD KNOWS WHICH FIELD TO USE
// FURTHER LOGIC WOULD BE HERE.
return ResponseEntity.ok(response);
}
I have read about Jackson Serialization but still finding solution for this.
Customize the Jackson ObjectMapper
Any help would be much appreciated.
You could just use a map for your input.
Then you can access filed in the map depending on what kind of fields it contains.
#PostMapping(value = "/lookup")
public ResponseEntity<AppResponse> getLookup(#RequestBody Map<String, Object> lookupRequestObject) {
// THIS METHOD KNOWS WHICH FIELD TO USE
// FURTHER LOGIC WOULD BE HERE.
return ResponseEntity.ok(response);
}
If JSON object structure is not known, you can always use Map<String, Object> type and convert it to POJO or directly work on Map. In case you need POJO you can use convertValue method:
#PostMapping(value = "/lookup")
public ResponseEntity<AppResponse> getLookup(#RequestBody Map<String, Object> payload) {
// read map
ObjectMapper objectMapper = new ObjectMapper();
if (payload.containsKey("seqNo")) {
Sequence seq = objectMapper.convertValue(payload, Sequence.class);
// other logic
} else if (payload.containsKey("country")) {
Country country = objectMapper.convertValue(payload, Country.class);
}
// the same for other types
// FURTHER LOGIC WOULD BE HERE.
return ResponseEntity.ok(response);
}
You can also try with deserialising to com.fasterxml.jackson.databind.JsonNode but it binds controller with Jackson which is not good from other side.
The answer by #Patrick Adler is absolutely correct. You can use Map as your parameter of the method. Two important additions: Map corresponds to JSON Object so when a JSON object is passed to your method Spring (using Jackson by default) will convert it to map, so no additional code needed. Also to be sure you can add to your annotation that you expect to receive JSON input:
So change the line
#PostMapping(value = "/lookup") to
#PostMapping(value = "/lookup", headers = "Accept=application/json") And finally the input that you posted is not a valid single JSON Object. It is 3 separate JSON Objects. So either you expect a JSON array containing JSON Objects or a Single JSON Object. If you expect a JSON Array then instead of Map<String, Object> parameter in your method use List<Map<String, Object>> so your solution should look either
#PostMapping(value = "/lookup", headers = "Accept=application/json")
public ResponseEntity<AppResponse> getLookup(#RequestBody Map<String, Object> lookupRequestObject) {
// THIS METHOD KNOWS WHICH FIELD TO USE
// FURTHER LOGIC WOULD BE HERE.
return ResponseEntity.ok(response);
}
or the same but with List<Map<String, Object>> param instead of just map

Serialize to JSON as name-value from String by Jackson ObjectMapper

I have some String, like:
String value = "123";
And when i serialize this string to json via ObjectMapper:
objectMapper.writeValueAsString(value);
Output is:
"123"
Is it possible to write String using either string name and string value? Desired output:
"value" : "123"
PS: i dont want to create DTO object with one field for serializing one String value.
you can also use the Jackson JsonGenerator
try (JsonGenerator generator = new JsonFactory().createGenerator(writer)) {
generator.writeStartObject();
generator.writeFieldName("value");
generator.writeString("123");
generator.writeEndObject();
}
}
If you have a plain string you'll get out a plain string when serialised. If you want to wrap it in an object then use a map for the simplest solution.
String value = "123";
Map<String, String> obj = new HashMap<>();
obj.put("value", value);
Passing that through the mapper will produce something like this:
{ "value": "123" }
If you change the map to <String, Object> you can pass in pretty much anything you want, even maps within maps and they'll serialise correctly.
If you really can't have the enclosing curly braces you can always take the substring but that would be a very weird use case if you're still serialising to JSON.
Create a Map:
Map<String, String> map = new HashMap<>();
map.put("value", value);
String parsedValue = ObjectMapper.writeValueAsString(map);
and you will get: {"value":"123"}
If you are using java 8 and want to do it in automated way without creating maps or manually putting string variable name "value", this is the link you need to follow-

Parsing dynamic JSON values to Java objects

In my application I have lot of overviews (tables) with sorting and filtering capabilities. And becuase the different column can hold different value type (strings, numbers, dates, sets, etc.) the filter for these columns also can bring different values. Let me show you few examples (converted to JSON already as is sent to server via REST request):
For simple string value it is like:
{"<column_name>":"<value>"}
For number and date column the filter looks like:
{"<column_name>":[{"operator":"eq","value":"<value>"}]}
{"<column_name>":[{"operator":"eq","value":"<value1>"},{"operator":"gt","value":"<value2>"}]}
For set the filter looks like
{"<column_name>":["<value1>","<value2>"(,...)]}
Now I need to parse that JSON within a helper class that will build the WHERE clause of SQL query. In PHP this is not a problem as I can call json_decode and then simply check whether some value is array, string or whatever else... But how to do this simply in Java?
So far I am using Spring's JsonJsonParser (I didn't find any visible difference between different parsers coming with Spring like Jackson, Gson and others).
I was thinking about creating an own data object class with three different constructors or having three data object classes for all of the three possibilities, but yet I have no clue how to deal with the value returned for column_name after the JSON is parsed by parser...
Simply looking on the examples it gives me three possibilities:
Map<String, String>
Map<String, Map<String, String>>
Map<String, String[]>
Any idea or clue?
Jackson's ObjectMapper treeToValue should be able to help you.
http://fasterxml.github.io/jackson-databind/javadoc/2.2.0/com/fasterxml/jackson/databind/ObjectMapper.html#treeToValue%28com.fasterxml.jackson.core.TreeNode,%20java.lang.Class%29
Your main problem is that the first version of you JSON is not the same construction than the two others. Picking the two others you could deserialize your JSON into a Map<String, Map<String, String> as you said but the first version fits a Map.
There are a couple solutions available to you :
You change the JSON format to always match the Map<String, Map<String, String> pattern
You first parse the JSON into a JsonNode, check the type of the value and deserialize the whole thing into the proper Map pattern.
(quick and dirty) You don't change the JSON, but you try with one of the Map patterns, catch JsonProcessingException, then retry with the other Map pattern
You'll have to check the type of the values in runtime. You can work with a Map<String, Object> or with JsonNode.
Map<String, Object>
JsonParser parser = JsonParserFactory.getJsonParser();
Map<String, Object> map = parser.parseMap(str);
Object filterValue = filter.get("<column_name>");
if (filterValue instanceof String) {
// str is like "{\"<column_name>\":\"<value>\"}"
} else if (filterValue instanceof Collection) {
for (Object arrayValue : (Collection<Object>) filterValue) {
if (arrayValue instanceof String) {
// str is like "{\"<column_name>\":[\"<value1>\",\"<value2>\"]}"
} else if (arrayValue instanceof Map) {
// str is like "{\"<column_name>\":[{\"operator\":\"eq\",\"value\":\"<value>\"}]}"
}
}
}
JsonNode
ObjectMapper mapper = new ObjectMapper();
JsonNode filter = mapper.readTree(str);
JsonNode filterValue = filter.get("<column_name>");
if (filterValue.isTextual()) {
// str is like "{\"<column_name>\":\"<value>\"}"
} else if (filterValue.isArray()) {
for (JsonNode arrayValue : filterValue.elements()) {
if (arrayValue.isTextual()) {
// str is like "{\"<column_name>\":[\"<value1>\",\"<value2>\"]}"
} else if (arrayValue.isObject()) {
// str is like "{\"<column_name>\":[{\"operator\":\"eq\",\"value\":\"<value>\"}]}"
}
}
}

Gson, JSON and the subtleties of LinkedTreeMap

I've recently started playing around with JSON strings, and was told that Google's own library, Gson, is the new and hip way of dealing with these.
The way I've understood it, is that a JSON string is essentially a map. Where each variable points to a value in the string.
For example:
String jsonInput2 = "{\"created_at\":\"Sat Feb 08 15:37:37 +0000 2014\",\"id\":432176397474623489\"}
Thus far, all is well. Information such as when this JSON string was created, can be assigned to a variable with the following code:
Gson gson = new Gson();
Map<String, String> map = new HashMap<String, String>();
map = (Map<String, String>) gson.fromJson(jsonInput, map.getClass());
String createdAt = map.get("created_at");
It's almost artistic in in simple beauty. But this is where the beauty ends and my confusion begins.
The following is an extension of the above JSON string;
String jsonInput2 = "{\"created_at\":\"Sat Feb 08 15:37:37 +0000 2014\",\"id\":432176397474623489\",\"user\":{\"id_str\":\"366301747\",\"name\":\"somethingClever\",\"screen_name\":\"somethingCoolAndClever\"}}";
My question is how these "brackets within brackets" work for the user section of the JSON?
How could I assign the values specified within these inner-brackets to variables?
Can anyone explain to me, or show me in code, how Gson handles stuff like this, and how I can use it?
In short, why does...
String jsonInput = "{\"created_at\":\"Sat Feb 08 15:37:37 +0000 2014\",\"id\":432176397474623489\",\"user\":{\"id_str\":\"366301747\",\"name\":\"somethingClever\",\"screen_name\":\"somethingCoolAndClever\"}}";
Gson gson = new Gson();
Map<String, String> map = new HashMap<String, String>();
map = (Map<String, String>) gson.fromJson(jsonInput, map.getClass());
String name = map.get("name");
System.out.println(name);
... print out null?
Forget about Java. You need to first understand the JSON format.
This is basically it
object
{}
{ members }
members
pair
pair , members
pair
string : value
array
[]
[ elements ]
elements
value
value , elements
value
string
number
object
array
true
false
null
Your second JSON String (which has a missing ") is the following (use jsonlint.com to format)
{
"created_at": "Sat Feb 08 15:37:37 +0000 2014",
"id": "432176397474623489",
"user": {
"id_str": "366301747",
"name": "somethingClever",
"screen_name": "somethingCoolAndClever"
}
}
The JSON is an object, outer {}, that contains three pairs, created_at which is a JSON string, id which is also a JSON string, and user which is a JSON object. That JSON object contains three more pairs which are all JSON strings.
You asked
How could I assign the values specified within these inner-brackets to
variables?
Most advanced JSON parsing/generating libraries are meant to convert JSON to Pojos and back.
So you could map your JSON format to Java classes.
class Pojo {
#SerializedName("created_at")
private String createdAt;
private String id;
private User user;
}
class User {
#SerializedName("id_str")
private String idStr;
private String name;
#SerializedName("screen_name")
private String screenName;
}
// with appropriate getters, setters, and a toString() method
Note the #SerializedName so that you can keep using Java naming conventions for your fields.
You can now deserialize your JSON
Gson gson = new Gson();
Pojo pojo = gson.fromJson(jsonInput2, Pojo.class);
System.out.println(pojo);
would print
Pojo [createdAt=Sat Feb 08 15:37:37 +0000 2014, id=432176397474623489", user=User [idStr=366301747, name=somethingClever, screenName=somethingCoolAndClever]]
showing that all the fields were set correctly.
Can anyone explain to me, or show me in code, how Gson handles stuff like this, and how I can use it?
The source code of Gson is freely available. You can find it online. It is complex and a source code explanation wouldn't fit here. Simply put, it uses the Class object you provide to determine how it will map the JSON pairs. It looks at the corresponding class's fields. If those fields are other classes, then it recurs until it has constructed a map of everything it needs to deserialize.
In short, why does...print out null?
Because your root JSON object, doesn't have a pair with name name. Instead of using Map, use Gson's JsonObject type.
JsonObject jsonObject = new Gson().fromJson(jsonInput2, JsonObject.class);
String name = jsonObject.get("user") // get the 'user' JsonElement
.getAsJsonObject() // get it as a JsonObject
.get("name") // get the nested 'name' JsonElement
.getAsString(); // get it as a String
System.out.println(name);
which prints
somethingClever
The above method class could have thrown a number of exceptions if they weren't the right type. If, for example, we had done
String name = jsonObject.get("user") // get the 'user' JsonElement
.getAsJsonArray() // get it as a JsonArray
it would fail because user is not a JSON array. Specifically, it would throw
Exception in thread "main" java.lang.IllegalStateException: This is not a JSON Array.
at com.google.gson.JsonElement.getAsJsonArray(JsonElement.java:106)
at com.spring.Example.main(Example.java:19)
So the JsonElement class (which is the parent class of JsonObject, JsonArray, and a few others) provides methods to check what it is. See the javadoc.
For people that come here searching for a way to convert LinkedTreeMap to object:
MyClass object = new Gson().fromJson(new Gson().toJson(((LinkedTreeMap<String, Object>) theLinkedTreeMapObject)), MyClass .class)
This was usefull for me when i needed to parse an generic object like:
Class fullObject {
private String name;
private String objectType;
private Object objectFull;
}
But i don't know which object the server was going to send. The objectFull will become a LinkedTreeMap
The JSON string has following structure:
{
created_at: "",
id: "",
user: {
id_str: "",
name: "",
screen_name: ""
}
}
When you put the values in the map using the code:
Map<String, Object> map = new HashMap<String, Object>();
map = (Map<String, Object>) gson.fromJson(jsonInput, map.getClass());
It has following key values:
created_at
id
user
and that's why you are able to use map.get("created_at").
Now, since you want to get the name of the user, you need to get the map of user:
LinkedTreeMap<String, Object> userMap = (LinkedTreeMap<String, Object>) map.get("user");
In the userMap, you would get following key values:
id_str
name
screen_name
Now, you can get the name of the user
String name = userMap.get("name");
user is a JsonObject itself:
JsonObject user = map.get("user");
Ok. First of all JSON is short for "JavaScript Object Notation" so your assertion that "a JSON string is essentially a map" is incorrect. A JSON block is an object graph, described using the JavaScript language syntax. Since your trying to coerce an object graph to a Map of String, Sting kay value pairs, this is only going to work in cases where any given JSON object graph is essentially just that (so not very often). A more successful strategy would probably be gson.fromJson() which will convert your JSON to a proper Java object graph.

Categories