Decoding JSON String for List with names - java

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);

Related

Create JSON String Array from Java List

I have a java.util.List containing Java POJOs that I want to render as JSON Array String. For example:
[
{ "name": "abc", "age": 50 },
{ "name": "def", "age": "25" }
];
Using Java EE JSON Api I have added:
public String createJsonArrayFromList(List<Person> list) {
JsonArrayBuilder jsonArray = Json.createArrayBuilder();
for(Person c : list) {
jsonArray.add(Json.createObjectBuilder()
.add("name", c.getName())
.add("surname", c.getSurname()));
}
JsonArray array =jsonArray.build();
return array.toString();
}
However, what is returned is not the JSON String array but "org.glassfish.json.JsonArrayBuilderImpl#761c5d2f"
I have attemped with:
StringWriter buffer = new StringWriter();
Json.createWriter(buffer).writeObject(array);
But writeObject expects a different object type rather than JsonArray.
Any help?
Use writeArray instead of writeObject:
JsonArray arr = ...;
JsonWriter writer = Json.createWriter(...)
writer.writeArray(arr);
writer.close();
See the docs.
You can use Gson Library which helps you better.
GsonBuilder builder=new GsonBuilder();
Gson gson=builder.create();
List<YourMeberClas> YourList=new ArrayList<>();
JsonElement je = gson.toJsonTree(YourList, new
TypeToken<List<YourMemberClass>>() {
}.getType());
With this you can easily access the data as well.

Get the keys from JSON Array into a list without Jackson

I have an service that returns me an json object like the below
{
"header": {},
"title": {},
"terms": {
"data": {
"list": [
"string": 1,
"string1": 2,
"string2": 3
]
}
}
}
Now I need to get the keys of the list json array into a list. I have got the array into an object
List<String> allTerms = new ArrayList<String>();
String response = HttpRequest.get("http://myservice/get").body();
JSONParser parser = new JSONParser();
Object obj = parser.parse(response);
JSONObject jsonObject = (JSONObject) obj;
JSONObject fieldObj = (JSONObject)jsonObject.get("terms");
JSONObject queryObj = (JSONObject)fieldObj.get("data");
JSONArray termsArr = (JSONArray) queryObj.get("list");
//iterate the termsarr and get the string,string1,string2 keys alone to allTerms list
Is there a more better way to do this? Im using json-simple and a custom http client
By using basic for loop
for(int i=0; i<termsArr.length(); i++) {
String[] arr = termsArr.getString(i).split("\"");
allTerms.add(arr[1]);
}

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);

Java GSON - make array from String of json

I want to make an array of product objects from a json file which is currently a String.
{
"invoice": {
"products": {
"product": [
{
"name": "Food",
"price": "5.00"
},
{
"name": "Drink",
"price": "2.00"
}
]
},
"total": "7.00"
}
}
...
String jsonString = readFile(file);
JsonParser parser = new JsonParser();
JsonObject jsonObject = parser.parse(jsonString).getAsJsonObject();
JsonArray jsonArray = jsonObject.getAsJsonArray("product");
the line below give me: java.lang.NullPointerException
for(JsonElement element: jsonArray) {
//do stuff
System.out.println(element);
}
some code goes here...
product = new Product(name, price);
List<Product> products = new ArrayList<Product>();
products.add(product);
You have to traverse the whole JSON string to get to the "product" part.
JsonArray jsonArray = jsonObject.get("invoice").getAsJsonObject().get("products").getAsJsonObject().get("product").getAsJsonArray();
I would recommend that you create a custom deserializer as described in the second answer to this question: How do I write a custom JSON deserializer for Gson? This will make it a lot cleaner, and let you handle improper JSON and make it easier in case your JSON ever changes.
I think you can use Gson library for this
You can find the project and the documentation at : https://github.com/google/gson/blob/master/README.md
try
String jsonString = readFile(file);
JsonParser parser = new JsonParser();
JsonObject invoice = parser.parse(jsonString).getAsJsonObject();
JsonObject products = invoice.getAsJsonObject("products");
JsonArray jsonArray = products.getAsJsonArray("product");

how to add Json header in json array parsed from Java Object

i found many examples to parse java object to Json.
Thanks for that.But i have one issue, i want Json in following format
{
"parent":
{
"sub-parent-1":
{
"child-1": 1,
"child-2": 2
},
"sub-parent-2":
{
"child-2": 3
}
}
}
Is it possible with java.
Please answer.Thanks in advanced..
Create Current Json String as in Java :
JSONObject parent = new JSONObject();
JSONObject subparentone = new JSONObject();
JSONObject subparenttwo = new JSONObject();
subparentone.put("child-1", "1");
subparentone.put("child-2", "2");
subparenttwo.put("child-2", "3");
parent.put("sub-parent-1", subparentone);
parent.put("sub-parent-2", subparenttwo);
JSONObject finalparent = new JSONObject();
finalparent.put("parent", parent);
and finalparent JsonObject output as:
{
"parent": {
"sub-parent-1": {
"child-1": 1,
"child-2": 2
},
"sub-parent-2": {
"child-2": 3
}
}
}
I have created class for parent and pass child to it. And convert that parent class into Json using Gson.

Categories

Resources