deserialize inner JSON object - java

I have a class POJO
Class Pojo {
String id;
String name;
//getter and setter
}
I have a json like
{
"response" : [
{
"id" : "1a",
"name" : "foo"
},
{
"id" : "1b",
"name" : "bar"
}
]
}
I am using Jackson ObjectMapper for deserialization. How can I get List<Pojo> without creating any other parent class?
If it is not possible, is it possible to get Pojo object which holds just first element of json string i.e. in this case id="1a" and name="foo"?

You'll first need to get the array
String jsonStr = "{\"response\" : [ { \"id\" : \"1a\", \"name\" : \"foo\"},{ \"id\" : \"1b\",\"name\" : \"bar\" } ]}";
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(jsonStr);
ArrayNode arrayNode = (ArrayNode) node.get("response");
System.out.println(arrayNode);
List<Pojo> pojos = mapper.readValue(arrayNode.toString(), new TypeReference<List<Pojo>>() {});
System.out.println(pojos);
prints (with a toString())
[{"id":"1a","name":"foo"},{"id":"1b","name":"bar"}] // the json array
[id = 1a, name = foo, id = 1b, name = bar] // the list contents

You can use the generic readTree with JsonNode:
ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(json);
JsonNode response = root.get("response");
List<Pojo> list = mapper.readValue(response, new TypeReference<List<Pojo>>() {});

Pojo pojo;
json = {
"response" : [
{
"id" : "1a",
"name" : "foo"
},
{
"id" : "1b",
"name" : "bar"
}
]
}
ObjectMapper mapper = new ObjectMapper();
JsonNode root = objectMapper.readTree(json);
pojo = objectMapper.readValue(root.path("response").toString(),new TypeReference<List<Pojo>>() {});
First, you have to create a JSON node with your JSON file. Now you have a JSON node. You can go to the desired location using path function of JSON node like what I did
root.path("response")
However this will return a JSON tree. To make a String, I have used the toString method.
Now, you have a String like below
"
[
{
"id" : "1a",
"name" : "foo"
},
{
"id" : "1b",
"name" : "bar"
}
] "
You can map this String with JSON array as following
String desiredString = root.path("response").toString();
pojos = objectMapper.readValue(desiredString ,new TypeReference<List<Pojo>>() {});

Related

How to customize a json that is created using Gson object in java

I have this JSON object that I've created using GSON:
{
"data": {
"isDeleted": false,
"period": 201601,
"columnMap": {
"1c49eb80-7b53-11e6-bc4b-afbeabb62718": "5000",
"1c49eb80-7b52-11e6-bc4b-afbeabb62718": "hello",
"03a534c0-a7f1-11e6-9cde-493bf5c47f4": "AUS",
"03a534c0-a7fa-11e6-9cde-493bf5c47f4": "123"
}
}
}
But my requirement is for it to look like
{
"data": {
"isDeleted": false,
"period": 201601,
"1c49eb80-7b53-11e6-bc4b-afbeabb62718": "5000",
"1c49eb80-7b52-11e6-bc4b-afbeabb62718": "hello",
"03a534c0-a7f1-11e6-9cde-493bf5c47f4": "AUS",
"03a534c0-a7fa-11e6-9cde-493bf5c47f4": "123"
}
}
}
How do I solve this, because all the values in "columnMap" are generated dynamically.
You need to create instance updateJsonObj of JsonObject to update key and value of columnMap using for each loop. Following code snippet is the solution :
String json = "{ \"data\": {\"isDeleted\": false,\"period\": 201601,"
+ "\"columnMap\": {\"1c49eb80-7b53-11e6-bc4b-afbeabb62718\": \"5000\","
+ "\"1c49eb80-7b52-11e6-bc4b-afbeabb62718\": \"hello\","
+ "\"03a534c0-a7f1-11e6-9cde-493bf5c47f4\": \"AUS\", "
+ "\"03a534c0-a7fa-11e6-9cde-493bf5c47f4\": \"123\"}}}";
Gson gson = new Gson();
JsonObject root = new JsonParser().parse(json).getAsJsonObject();
JsonElement dataElement = root.get("data");
// cobj has value of colummMap of json data
JsonObject cobj = (JsonObject) root.get("data").getAsJsonObject().get("columnMap");
JsonObject updateJsonObj = root;
// remove columnMap node as you wanted !
updateJsonObj.get("data").getAsJsonObject().remove("columnMap");
for (Entry<String, JsonElement> e : cobj.entrySet()) {
//update updateJsonObj root node with key and value of columnMap
updateJsonObj.get("data").getAsJsonObject().addProperty(e.getKey(), e.getValue().getAsString());
}
String updateJson = gson.toJson(updateJsonObj);
System.out.println(updateJson);

Getting Json Titled json Array without using pojo , bean, or getter and setter

Hi I've just started to use Json.
My problem is I want json array in following form
[ { "id" : "1", "name" : "India" },{ "id" : "2", "name" : "Pakistan" },{ "id" : "3", "name" : "China" },{ "id" : "4", "name" : "Japan" },{ "id" : "5", "name" : "Russia" } ]
I want id and name title for every value.
Then biggest problem is when I am sending this json to ajax using servlet I am getting nothing (using this code)
List<stateList> sl = new ArrayList<stateList>();//ststeList is getters n setters obj
sl.add(new stateList("1","India"));
Gson js = new Gson();
js.toJson(sl);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(js.toString());
but if I use string object I am getting the value but without titles i.e (id,name)
{"1":"India","2":"Pak","3":"China"}
Code is
Map<String,String> m = new HashMap<String, String>();
m.put("1", "India");
m.put("2", "Pak");
m.put("3", "China");
String js = new Gson().toJson(m);
So finally I want above most json to send to ajax.There is no proble with ajax code its working fine with this type
Use entrySet to get the keys. Just loop through the entries
Code :
JsonParser p = new JsonParser();
JsonObject result = p.parse(file).getAsJsonObject();
Set<Map.Entry<String, JsonElement>> entrySet = result.entrySet();
for(Map.Entry<String, JsonElement> entry : entrySet) {
System.out.println(entry.getKey()); //this gives you the keys.
}
I hope this helps you
Ok after lots of toiling I got the solution which is already hidden in the class I built previously.
class stateList
{
private String id;
private String StateName;
stateList s;
public stateList(String id, String StateName)
{
this.id = id;
this.StateName = StateName;
}
public String toString() {
return "id = " +id+ ", stateName = " +StateName; //solution
}
}
just call the stateList's toString();
//code 2 line 5
js = new Gson().toJson(sl.toString());

Jackson: Cannot deserialize instance of object out of START_ARRAY

I'm getting this error when attempting to parse some JSON previously generated with Jackson. I generate the JSON like so
String ret = "";
ret = mapper.writeValueAsString(message.getPayload());
message.setPayload(ret);
Where message.getPayload() is a HashMap, in this instance containing two strings and a List of various objects. This creates the following malformed JSON
{
"user" : "john d example",
"items" : [ {
"val" : 99.5,
"id" : "phone",
"qty" : 1
}, {
"val" : 15.5,
"id" : "wine",
"qty" : 4
} ],
"address" : "123 example street"
}
Which throws an exception when examined thusly
Map<String, Object> ret = new HashMap<String, Object>();
String s = (String)message.getPayload();
ret = mapper.readValue(s, new TypeReference<Map<String, String>>(){});
How should I properly write this Map to JSON?
TypeReference<Map<String, String>> should be TypeReference<Map<String, Object>>. Jackson is attempting to parse the values as Strings rather than Lists because that is what it expects based on the TypeReference you passed in.

Decoding JSON String for List with names

I am try to decode a JSON string as below
{
"id_value": [
{
"id": "1.1.1.1",
"value": "v1"
},
{
"id": "1.1.1.2",
"value": "v2"
}
]
}
Which is basically a list of id_value object. IdValue is a POJO class with a string variable of id and value.
I am able to decode the JSON string , when I passed in JSON without the list name , as below.
[
{
"id": "1.1.1.1",
"value": "v1"
},
{
"id": "1.1.1.2",
"value": "v2"
}
]
My JAVA code is as below :
String jsonString1 = "{\"id_value\": [{\"id\": \"1.1.1.1\",\"value\": \"v1\"},{\"id\": \"1.1.1.2\",\"value\": \"v2\"}]}";
String jsonString2 = "[{\"id\": \"1.1.1.1\",\"value\": \"v1\"},{\"id\": \"1.1.1.2\",\"value\": \"v2\"}]";
List<IdValue> idValues = null;
try {
Gson gson = new Gson();
idValues = gson.fromJson(jsonString2, new TypeToken<List<IdValue>>(){}.getType());
}
catch (Exception e) {
e.printStackTrace();
}
System.out.println(idValues);
My code works well with jsonString2 , but I am getting the below exception with jsonString1. Both of them are lists , but why it is failing for one and working for other.
com.google.gson.JsonParseException: The JsonDeserializer com.google.gson.DefaultTypeAdapters$CollectionTypeAdapter#67ac19 failed to deserialize json object {"id_value":[{"id":"1.1.1.1","value":"v1"},{"id":"1.1.1.2","value":"v2"}]} given the type java.util.List<com.something.json.IdValue>
Any inputs would be helpful.
Thanks !!
jsonString2 represents a List<IdValue>
jsonString1 represents a Map<String, List<IdValue>>
So, to process jsonString1 you need:
Map<String, List<IdValue>> map = gson.fromJson(json, new TypeToken<Map<String, List<IdValue>>>(){}.getType());
List<idValue> idValues = map.get("id_value");
Here is more general way to get your IdValues from jsonString1 even if there are another entries in it:
Gson gson = new Gson();
JsonParser parser = new JsonParser();
String jsonString1 = "{\"id_value\": [{\"id\": \"1.1.1.1\",\"value\": \"v1\"},{\"id\": \"1.1.1.2\",\"value\": \"v2\"}]}";
JsonElement e = parser.parse(jsonString1);
JsonArray idValueArray = e.getAsJsonObject().getAsJsonArray("id_value");
List<IdValue> idValues = gson.fromJson(idValueArray, new TypeToken<List<IdValue>>(){}.getType());
id_value isn't part of your IdValue POJO. So the TypeToken of List does not know how to map the id_value piece of the JSON string.
Because jsonString1's deserializing type is not same with jsonString2's. If you want to use same deserializing type, you should first do substring.
jsonString1 = jsonString1.substring(s.indexOf("["));
jsonString1 = jsonString1.substring(0, s.lastIndexOf("]") + 1);

De-serialize List of POJOs rather than a single one at a time

So I came across this tutorial for serializing a POJO to json and then de-serialize the json file back to the POJO. http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/
he uses these helpful methods which worked for me but only for a single POJO in the file:
//1. Convert Java object to JSON format
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(new File("c:\\user.json"), user);
//2. Convert JSON to Java object
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(new File("c:\\user.json"), User.class);
How can I de-serialize a list of POJOs? My serialized file looks like the below:
[ {
"name" : {
"first" : "Wonder",
"last" : "Woman"
},
"ssn" : "123-456-7890",
"gender" : "FEMALE",
"verified" : false
}, {
"name" : {
"first" : "Bat",
"last" : "Man"
},
"ssn" : "321-456-0987",
"gender" : "FEMALE",
"verified" : true
}, {
"name" : {
"first" : "Super",
"last" : "Man"
},
"ssn" : "321-654-1111",
"gender" : "FEMALE",
"verified" : true
} ]
One option (probably the easiest) is to define a class that contains a list of Users:
public class Users
{
public User[] users;
}
Then performing
ObjectMapper mapper = new ObjectMapper();
Users users = mapper.readValue(new File("c:\\user.json"), Users.class);
Another option would be to iterate over the json array, and capture each element of the array of users, then use ObjectMapper.readValue(String content, Class<T> valueType), like so:
ObjectMapper mapper = new ObjectMapper();
InputStream stream = new FileInputStream("c:\\user.json");
User user;
JsonNode json = mapper.readTree(stream);
//NOTE: calling json.isArray() should return true.
for (JsonNode userJson : json)
{
user = mapper.readValue(userJson, User.class);
// use the constructed user...
}
Note: I haven't tested the above, so let me know if it works or not.
Hmmh? Have you tried:
User[] users = mapper.readValue(new File("c:\\user.json"), User[].class);
In your top level class, you have an array of people. something like this
class People {
public List<Person> persons;
}

Categories

Resources