How to parse json object with different key values? - java

We are trying to parse an json object which is having different key-values everytime.
{
"Key1": "Val1",
"Key2": "Val2",
"Key3": "Val3",
"Key4": "Val4",
"Key5": "Val5",
.........,
.........,
"KeyN": "ValN"
}
Here "KeyN" can have different names also "ValueN" also will be different.
It is very clear that this will not parse in one go, like :
ObjectX objetX = new Gson().fromJson(sourceJson, ObjectX.class);
How should we parse this ? even if we choose to parse manually ? We trying this in android Volley response.

Using Gson java library parse your json object into HashMap<String,String>.
sample code
sourceJson = {
"Key1": "Val1",
"Key2": "Val2",
"Key3": "Val3",
"Key4": "Val4",
"Key5": "Val5",
.........,
.........,
"KeyN": "ValN"
};
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> myMap = gson.fromJson(sourceJson, type);
If you want more generic solution should be
Map map = gson.fromJson(sourceJson, Map.class);

Related

Java Spring custom JSON response

I have a data that looks like so:
{
"name":{
"first": "<firstName>",
"last": "<lastName>"
},
"info": "<info>",
"place":{
"location": "<location>",
},
"test": "<test>"
}
However, I want to customize the Response json and group the data by the location.
In other words I would like to have a response like this:
"location":[{
"name": <location>,
user: [{
"name": <firstName> + <lastName>,
"info": <info>,
"test": <test>
}]
}]
I have tried to the it into a map like so:
List<Data> data= newArrayList(repository.findAll(Sort.by(Sort.Direction.ASC, "location")));
Map<String, Object> result= new HashMap<>();
for (Data d : data) {
result.put("name", d.getLocation());
result.put("user", d.getFirstName());
...
and so on, but this does not work. What is the best approach to achieve my desired result?
As of now you have a single result map, which you are then overwriting in the loop, so it will contain data for a location only, the last one. What you probably wanted to do is creating a list of those maps, which requires creating a new map inside the loop, and collecting them in a list:
List<Map<String, Object>> result=new ArrayList<>();
for(Data d : data) {
Map<String, Object> item = new HashMap<>();
item.put("name", d.getLocation());
item.put("user", d.getFirstName());
...
result.add(item);
}

Using Jackson, how can you get a list of objects from an interesting json?

I have this json, I need to get a list of currency objects using Jackson (the objects itself has a currency name field - "USD", "type" and "show") as a result. How can I do it in a simple and clear way?
Any help would be welcome
{
...
"result": "OK",
"currency": {
"currencies": {
"LB": {
"type": "A",
"setting": {
"show": true,
},
"access" : true
},
"USD": {
"type": "B",
"setting": {
"show": true,
},
"access" : true
},
"RUB": {
"type": "A",
"setting": {
"show": true,
},
"access" : true
},
....
// and more..
},
...
}
}
"currencies": {
"LB": {
"type": "A",
"setting": {
"show": true,
},
"access" : true
},
"USD": {
"type": "B",
"setting": {
"show": true,
},
"access" : true
},
"RUB": {
"type": "A",
"setting": {
"show": true,
},
"access" : true
},
....
// and more..
},
...
This looks like an Map, not a List. Does that help you? So you would need to create Currency class and have jackson parse this structure to Map<String, Currency>. Note that currency will not contain the identifier (like "USD"), only they key in the map will.
You can read your Json as a Map<String, Object>. Once you have the map you iterate through your map and build your List.
If you want to de-serialize (read) from Json to List of your custom objects you need to have your Json restructured to be Json List and not Json Object. Then you can read your Json into a List directly. In any case, there is an Open source Library that has a feature based on Jackson library really simplifies reading/writing objects from/to Json. If you have a json string all you have to do is:
Map<String, Object> map = JsonUtils.readObjectFromJsonString(jsonString, Map.class);
It throws IOException though, so you will need to handle it. Here is the Javadoc. The library is called MgntUtils and could be found as Maven artifact and on the Github (including javadoc and source code)
I was able to add object saving to the list, but in a rather inconvenient way, it seems to me...
ArrayList<Dto> currencyObjectList = new ArrayList<Dto>();
CurrencyStaticDto obj = null;
JsonNode currencies = mapper.readTree(response.getBody()).get("currencies");
Iterator<Map.Entry<String, JsonNode>> fields = currencies.fields();
while(fields.hasNext()) {
Map.Entry<String, JsonNode> field = fields.next();
String fieldName = field.getKey();
JsonNode fieldValue = field.getValue();
obj = mapper.readValue(fieldValue.toString(),CurrencyStaticDto.class);
obj.setCurrency(fieldName);
currencyObjectList.add(obj);
}

how to read value key form a Json Element in Java

I have a jsonElement as following
how can I retrieve "value2" with minimal amount of coding?
{
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
Add jar in your project : org.json.
Suppose that you are having string,
String yourString = "{ \"key1\": \"value1\",\"key2\": \"value2\",\"key3\":\"value3\" }"
JSONObject jsonObj = new JSONObject(yourString);
First of all, check the desired key which you want to access to avoid nullPointer exception , then access you value . i.e.
Note: It is always a good practice to check whether this exists but in your case not mandatory
if(jsonObj.contains("key2") {
String key2 = jsonObj.getString("key2");
}

parse Json to Map<String,String>

I have Json response like :
[
{
"first_name": "fname1",
"last_name": "lname1"
},
{
"first_name": "fname2",
"last_name": "lname2",
"city_name": "paris"
},
{
"first_name": "fname2",
"last_name": "lname2",
"city_name": "paris",
"Address": "1st Ave"
}
.
.
.
]
and my fields in JsonObject is dynamic so i can't use a class with predefined fields , so i've decided to use Map to parse the Json response as below :
Collection<List<Map<String,String>>> list_Objects = null;
Reader reader = new InputStreamReader(is);
Gson gson = new Gson();
Type collectionType = new TypeToken<Collection<List<Map<String,String>>>>(){}.getType();
list_objects = gson.fromJson(reader, collectionType);
but it throws me this error :
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 1
im not expert in Json parsing so please tell me where is my mistake or if there is another way to implement such behavior i would be very appreciated.
I think the problem is with your Collection wrapper on the List one.
You just need to define the list_Objects as List<Map<String, String>>.
I just tried the following with Jackson's ObjectMapper (which should work the same as GSON) and it worked ok:
List<Map<String, String>> list_objects = objectMapper.readValue(jsonString, new TypeReference<List<Map<String, String>>>(){});
The result is a List of LinkedHashMap objects.
For your GSON example, you just need to remove the Collection<>, or the List<> if you prefer.
If I'm reading this correctly, you're defining your list twice.
Collection<List<Map<String, String>>> would map to a structure like
[ [ {"bla": "bla"}, {"bla": "bla"} ], [ {"foo": "bar"}, ... ], ... ]
(because List is a kind of Collection). So, try using List<Map<String, String>> and see if that works...

How to parse this JSON with GSON?

I'am struggling with a problem to parse a JSON with GSON which contains lists as values. This should be pretty simple, but I can't figure out how to solve it. The JSON is:
{
"key1": [
"foo1",
"foo2",
"foo3"
],
"key2": [
"foo4",
"foo5",
"foo6"
],
"key3": [
"foo7",
"foo8",
"foo9"
]
}
I think the best way is to put it into a Map<String, List<String>>, but I can't create a Type for it. Like:
Type jsonArrayType = new TypeToken<Map<String, List<String>>>(){}.getType();
// Doesn't work, causes exception: "com.google.gson.internal.LinkedTreeMap cannot be cast to java.util.List"
Thanks for any help!
You will get a java.lang.reflect.Type from the getType() method. Use that to parse your json. Here is a small working example (Java 7)
String json = "{\"key1\": [\"foo1\",\"foo2\",\"foo3\"],\"key2\": [\"foo4\",\"foo5\",\"foo6\"],\"key3\": [\"foo7\",\"foo8\",\"foo9\"]}";
java.lang.reflect.Type type = new TypeToken<Map<String, List<String>>>(){}.getType();
Map<String, List<String>> map = new Gson().fromJson(json, type);
System.out.println(map);
This snippet prints the below value
{key1=[foo1, foo2, foo3], key2=[foo4, foo5, foo6], key3=[foo7, foo8, foo9]}

Categories