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");
Related
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.
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 can I extract JSON Array and JSON Object from JSON.
Below is the input:
{
"messageName": "ReportCard",
"orgId": "Org1",
"comment": true,
"Fields": [{
"objectId": "1234-56789-asdv",
"fieldId": "1245-7852-dhjd"
},
{
"objectId": "1234-56hgjgh789-hjjhj",
"fieldId": "12sdf45-78sfg52-dfjhjd"
}]
}
I want JSON Array and JSON Object separately and output should be like:
JSONArray
"Fields":[{ "objectId": "1234-56789-asdv",
"fieldId": "1245-7852-dhjd"},{
"objectId": "1234-56hgjgh789-hjjhj",
"fieldId": "12sdf45-78sfg52-dfjhjd"}]
and JSON Object should be like:
{
"messageName": "ReportCard",
"orgId": "Org1",
"comment": true
}
its pretty simple if you know java JSON API
String jsonString="{
"messageName": "ReportCard",
"orgId": "Org1",
"comment": true,
"Fields": [{
"objectId": "1234-56789-asdv",
"fieldId": "1245-7852-dhjd"
},
{
"objectId": "1234-56hgjgh789-hjjhj",
"fieldId": "12sdf45-78sfg52-dfjhjd"
}]
}"
JSONObject jObject= new JSONObject(jsonString);
JSONObject jo = new JSONObject(); //creating new Jobject
// putting data to JSONObject
jo.put("messageName", jObject.getString("messageName").toString());
jo.put("orgId", jObject.getString("orgId").toString());
jo.put("comment", jObject.getString("comment").toString());
JSONArray Fields= jObject.getJSONArray("Fields");//extract field array
JSONArray ja = new JSONArray(); //creating new json array.
int Arraylength = Fields.length();
for(int i=0;i<Arraylength;i++)
{
Map m = new LinkedHashMap(2);
JSONObject ArrayjObj = Fields.getJSONObject(i);
m.put("objectId", ArrayjObj.getString("objectId").toString());
m.put("fieldId", ArrayjObj.getString("fieldId").toString());
// adding map to list
ja.add(m);
}
JSONObject fieldsObj = new JSONObject();
fieldsObj.put("Fields", ja); // Fields Array Created
for JSON api refer this
you can fetch particular values as per keys into a json object and rest into a separate json array
String strJSON =" {\"id\":\"12\",\"messageName\":\"ReportCard\" , \"Fields\":[{\"objectId\": \"1234-56789-asdv\", \"fieldId\": \"1245-7852-dhjd\"},{\"objectId\": \"1234-56hgjgh789-hjjhj\", \"fieldId\": \"12sdf45-78sfg52-dfjhjd\"}] }";
JSONArray ja = new JSONArray();
JSONObject jo1= new JSONObject();
JSONObject jo= new JSONObject(strJSON);
ja= jo.getJSONArray( "Fields");
jo1.put("messageName",jo.get(messageName));
jo1.put("orgId",jo.get(orgId));
I have searched everywhere and cannot find out how to do this, I'm super stuck. I have NO experience with JSON files, so spoon feeding is appreciated along with an explanation.
I have this JSON text here for testing:
{
"id":"4566e69fc90748ee8d71d7ba5aa00d20",
"properties":
[
{
"name":"textures",
"value":"eyJ0aW1lc3RhbXAiOjE0ODI4ODAxNDMwNzYsInByb2ZpbGVJZCI6IjQ1NjZlNjlmYzkwNzQ4ZWU4ZDcxZDdiYTVhYTAwZDIwIiwicHJvZmlsZU5hbWUiOiJUaGlua29mZGVhdGgiLCJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMTNlODFiOWUxOWFiMWVmMTdhOTBjMGFhNGUxMDg1ZmMxM2NkNDdjZWQ1YTdhMWE0OTI4MDNiMzU2MWU0YTE1YiJ9LCJDQVBFIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMjJiOWM1ZWE3NjNjODZmYzVjYWVhMzNkODJiMGZhNjVhN2MyMjhmZDMyMWJhNTQ3NjZlYTk1YTNkMGI5NzkzIn19fQ==",
},
],
"name":"Thinkofdeath",
}
I currently have this:
JsonElement playerProfile = new JsonParser().parse(jsonLine);
JsonObject jsonProfile = playerProfile.getAsJsonObject();
JsonArray properties = jsonProfile.getAsJsonArray("properties");
Which returns
[
[
{
"name":"textures",
"value":"eyJ0aW1lc3RhbXAiOjE0ODI4ODAxNDMwNzYsInByb2ZpbGVJZCI6IjQ1NjZlNjlmYzkwNzQ4ZWU4ZDcxZDdiYTVhYTAwZDIwIiwicHJvZmlsZU5hbWUiOiJUaGlua29mZGVhdGgiLCJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMTNlODFiOWUxOWFiMWVmMTdhOTBjMGFhNGUxMDg1ZmMxM2NkNDdjZWQ1YTdhMWE0OTI4MDNiMzU2MWU0YTE1YiJ9LCJDQVBFIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMjJiOWM1ZWE3NjNjODZmYzVjYWVhMzNkODJiMGZhNjVhN2MyMjhmZDMyMWJhNTQ3NjZlYTk1YTNkMGI5NzkzIn19fQ==",
},
]
Of course. How do I get the "value" from this JsonArray? Note I'm using Google's API, Gson
You can get values using:
JsonObject propertiesJson = properties.get(0);
String value = propertiesJson.getString("value");
array is JsonArray object from com.google.gson library
for (int i=0; i<array.size(); i++) {
JsonObject json = array.get(i).getAsJsonObject();
String value = json.get("key").getAsString();
}
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);