Create JSON String Array from Java List - java

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.

Related

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

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

Getting a Value from a JsonArray using gson

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

JSON To ArrayList<CustomObject> With GSON While Ignoring Certain Fields

I am looking to create an ArrayList of custom objects from a JSON feed using GSON. My current approach works fine for a single JSON object holding an array, but now I need to parse a more complex JSON object. The first JSON feed looked like this:
{"data":
{"item_id": "1", "element": "element1"}
{"item_id": "2", "element": "element2"}
{"item_id": "3", "element": "element3"}
...
}
My method for extracting each item was using a simple custom object and parsing the JSON into an ArrayList of these objects.
InputStreamReader input = new InputStreamReader(connection.getInputStream());
Type listType = new TypeToken<Map<String, ArrayList<CustomObject>>>(){}.getType();
Gson gson = new GsonBuilder().create();
Map<String, ArrayList<CustomObject>> tree = gson.fromJson(input, listType);
ArrayList<CustomObject> = tree.get("data");
The current JSON object looks like this:
{"rate_limit": 1, "api_version": "1.2", "generated_on": "2015-11-05T19:34:06+00:00", "data": [
{"collection": [
{"item_id": "1", "time": "2015-11-05T14:40:55-05:00"},
{"item_id": "2", "time": "2015-11-05T14:49:09-05:00"},
{"item_id": "3", "time": "2015-11-05T14:51:55-05:00"}
], "collection_id": "1"},
{"collection": [
{"item_id": "1", "time": "2015-11-05T14:52:01-05:00"},
{"item_id": "2", "time": "2015-11-05T14:49:09-05:00"},
{"item_id": "3", "time": "2015-11-05T14:51:55-05:00"}
], "collection_id": "2"
]}
And I am having trouble parsing it because of the mixed types of data, some are numbers, strings and lastly arrays. I have a custom object built that takes an array of another custom object. This is the collection object:
public class CustomCollection {
private String collection_id;
private ArrayList<CustomItem> collection_items = new ArrayList<>();
public CustomCollection() {
this(null, null);
}
public CustomCollection(String id, ArrayList<CustomItem> items) {
collection_id = id;
collection_items = items;
}
public String getId() {
return collection_id;
}
public ArrayList<CustomItem> getItems() {
return collection_items;
}
}
And this is the item object:
public class CustomItem {
private String item_id;
private String item_element;
public CustomItem() {
this(null, null);
}
public CustomItem(String id, String element) {
item_id = id;
item_element = element;
}
public String getId() {
return item_id;
}
public String getElement() {
return item_element;
}
}
I do not really care about obtaining the other elements (i.e. "rate_limit", "api_version", "generated_on"), I just want to pass the "data" element into an ArrayList of objects. But when I try something similar to my original method, the parser stops a the first object because it receives a number instead of an array. Resulting in an IllegalStateException: Expected BEGIN_ARRAY but was NUMBER at line 1 column 17 path $.. I would like to know how I can either get the parser to ignore the other elements, or how I can get each element separately using GSON.
EDIT: The proposed solution to my problem, found in Ignore Fields When Parsing JSON to Object, technically does solve my issue. But this seems like a lengthy process that is unnecessary in my case. I have found a much simpler solution to my problem, posted in my answer below. I am also unsure if this method would work well for the aforementioned question, considering there does not seem to be a way to get a JsonObject from a JsonArray by key name in GSON.
The solution I have found is to parse the data into a com.google.gson.JsonObject, then into a JsonArray by key name. I can then use this JsonArray as a parameter in Gson.fromJson() to extract the data into my ArrayList of custom objects.
InputStreamReader input = new InputStreamReader(connection.getInputStream());
JsonArray data = new JsonParser().parse(input).getAsJsonObject().getAsJsonArray("data");
Type listType = new TypeToken<ArrayList<CustomCollection>>(){}.getType();
ArrayList<CustomCollection> collection = new Gson().fromJson(data, listType);
input.close();
This method ignores all other JSON fields, only obtaining the one specified. It also takes the array of objects from within the "data" object and puts them into the ArrayList of custom objects within CustomCollection.

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

Categories

Resources