I have a JsonObject named "mapping" with the following content:
{
"client": "127.0.0.1",
"servers": [
"8.8.8.8",
"8.8.4.4",
"156.154.70.1",
"156.154.71.1"
]
}
I know I can get the array "servers" with:
mapping.get("servers").getAsJsonArray()
And now I want to parse that JsonArray into a java.util.List...
What is the easiest way to do this?
Definitely the easiest way to do that is using Gson's default parsing function fromJson().
There is an implementation of this function suitable for when you need to deserialize into any ParameterizedType (e.g., any List), which is fromJson(JsonElement json, Type typeOfT).
In your case, you just need to get the Type of a List<String> and then parse the JSON array into that Type, like this:
import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;
JsonElement yourJson = mapping.get("servers");
Type listType = new TypeToken<List<String>>() {}.getType();
List<String> yourList = new Gson().fromJson(yourJson, listType);
In your case yourJson is a JsonElement, but it could also be a String, any Reader or a JsonReader.
You may want to take a look at Gson API documentation.
Below code is using com.google.gson.JsonArray.
I have printed the number of element in list as well as the elements in List
import java.util.ArrayList;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class Test {
static String str = "{ "+
"\"client\":\"127.0.0.1\"," +
"\"servers\":[" +
" \"8.8.8.8\"," +
" \"8.8.4.4\"," +
" \"156.154.70.1\"," +
" \"156.154.71.1\" " +
" ]" +
"}";
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
JsonParser jsonParser = new JsonParser();
JsonObject jo = (JsonObject)jsonParser.parse(str);
JsonArray jsonArr = jo.getAsJsonArray("servers");
//jsonArr.
Gson googleJson = new Gson();
ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class);
System.out.println("List size is : "+jsonObjList.size());
System.out.println("List Elements are : "+jsonObjList.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
OUTPUT
List size is : 4
List Elements are : [8.8.8.8, 8.8.4.4, 156.154.70.1, 156.154.71.1]
I read solution from official website of Gson at here
And this code for you:
String json = "{"client":"127.0.0.1","servers":["8.8.8.8","8.8.4.4","156.154.70.1","156.154.71.1"]}";
JsonObject jsonObject = new Gson().fromJson(json, JsonObject.class);
JsonArray jsonArray = jsonObject.getAsJsonArray("servers");
String[] arrName = new Gson().fromJson(jsonArray, String[].class);
List<String> lstName = new ArrayList<>();
lstName = Arrays.asList(arrName);
for (String str : lstName) {
System.out.println(str);
}
Result show on monitor:
8.8.8.8
8.8.4.4
156.154.70.1
156.154.71.1
I was able to get the list mapping to work with just using #SerializedName for all fields.. no logic around Type was necessary.
Running the code - in step #4 below - through the debugger, I am able to observe that the List<ContentImage> mGalleryImages object populated with the JSON data
Here's an example:
1. The JSON
{
"name": "Some House",
"gallery": [
{
"description": "Nice 300sqft. den.jpg",
"photo_url": "image/den.jpg"
},
{
"description": "Floor Plan",
"photo_url": "image/floor_plan.jpg"
}
]
}
2. Java class with the List
public class FocusArea {
#SerializedName("name")
private String mName;
#SerializedName("gallery")
private List<ContentImage> mGalleryImages;
}
3. Java class for the List items
public class ContentImage {
#SerializedName("description")
private String mDescription;
#SerializedName("photo_url")
private String mPhotoUrl;
// getters/setters ..
}
4. The Java code that processes the JSON
for (String key : focusAreaKeys) {
JsonElement sectionElement = sectionsJsonObject.get(key);
FocusArea focusArea = gson.fromJson(sectionElement, FocusArea.class);
}
Kotlin Extension
for Kotlin developers you can use this extension
inline fun <reified T> String.convertToListObject(): List<T>? {
val listType: Type = object : TypeToken<List<T?>?>() {}.type
return Gson().fromJson<List<T>>(this, listType)
}
Given you start with mapping.get("servers").getAsJsonArray(), if you have access to Guava Streams, you can do the below one-liner:
List<String> servers = Streams.stream(jsonArray.iterator())
.map(je -> je.getAsString())
.collect(Collectors.toList());
Note StreamSupport won't be able to work on JsonElement type, so it is insufficient.
Related
I have an Object array which is a list of argument values a function could take. This could be any complex object.
I am trying to build a json out of the Object array using gson as below:
private JsonArray createArgsJsonArray(Object... argVals) {
JsonArray argsArray = new JsonArray();
Arrays.stream(argVals).forEach(arg -> argsArray.add(gson.toJson(arg)));
return argsArray;
}
This treats all the arg values as String.
It escapes the String args
"args":["\"STRING\"","1251996697","85"]
I prefer the following output:
"args":["STRING",1251996697,85]
Is there a way to achieve this using gson?
I used org.json, I was able to achieve the desired result, but it does not work for complex objects.
EDIT:
I applied the solution provided by #MichaĆ Ziober, but now how do I get back the object.
Gson gson = new Gson();
Object strObj = "'";
JsonObject fnObj = new JsonObject();
JsonObject fnObj2 = new JsonObject();
fnObj.add("response", gson.toJsonTree(strObj));
fnObj2.addProperty("response", gson.toJson(strObj));
System.out.println(gson.fromJson(fnObj.toString(),
Object.class)); --> prints {response='} //Not what I want!
System.out.println(gson.fromJson(fnObj2.toString(),
Object.class)); --> prints {response="\u0027"}
Use toJsonTree method:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import java.util.Date;
public class GsonApp {
public static void main(String[] args) {
GsonApp app = new GsonApp();
System.out.println(app.createArgsJsonArray("text", 1, 12.2D));
System.out.println(app.createArgsJsonArray(new Date(), new A(), new String[] {"A", "B"}));
}
private Gson gson = new GsonBuilder().create();
private JsonArray createArgsJsonArray(Object... argVals) {
JsonArray argsArray = new JsonArray();
for (Object arg : argVals) {
argsArray.add(gson.toJsonTree(arg));
}
return argsArray;
}
}
class A {
private int id = 12;
}
Above code prints:
["text",1,12.2]
["Sep 19, 2019 3:25:20 PM",{"id":12},["A","B"]]
If you want to end up with a String, just do:
private String createArgsJsonArray(Object... argVals) {
Gson gson = new Gson();
return gson.toJson(argVals);
}
If you wish to collect it back and alter just do:
Object[] o = new Gson().fromJson(argValsStr, Object[].class);
Try using setPrettyPrinting with DisableHtml escaping.
Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create();
JsonParser jp = new JsonParser();
JsonElement je = jp.parse(jsonArray.toString());
System.out.println( gson.toJson(je));
'NextTo' signifies which regions.
Stuck on parsing.
Yes, your pseudo-code is the right way to go.
Start by deserializing your JSON string with Jackson (find the appropriate "model", e.g. nextTo can be mapped to a Map<Integer, List<Integer>>) then implement your pseudo-code.
Deserialise object using org.json,
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
public class DesrialiseJSON {
public static void main(String[] args) {
JSONParser parser = new JSONParser();
//json string
String stringToParse="{\"Regions\" : [{\"regionId\" : 5,\"name\" : \"South Korea\"},{\"regionId\" : 6,\"name\" : \"North Korea\"},{ }],\"nextTo\" : { \"5\" : [6], \"6\" : [5]}}";
try {
//convert to json object
JSONObject json = (JSONObject) parser.parse(stringToParse);
System.out.println(checkNextTo(json));
} catch (ParseException e) {
e.printStackTrace();
}
}
public static boolean checkNextTo(JSONObject json) {
//regions array
JSONArray regionArr=(JSONArray) json.get("Regions");
// Find the id of region1 in the "region" part of the JSON
long regionId1=(Long) ((JSONObject) regionArr.get(0)).get("regionId");
// Find the id of region2 in the "region" part of the JSON
long regionId2=(Long) ((JSONObject) regionArr.get(1)).get("regionId");
JSONObject nextTo=(JSONObject) json.get("nextTo");
Long nextToReg1=(Long) ((JSONArray) nextTo.get(String.valueOf(regionId1))).get(0);
Long nextToReg2=(Long) ((JSONArray) nextTo.get(String.valueOf(regionId2))).get(0);
// Check region1's nextTo regions in the "nextTo" section ofJSON
// If region2 id is in region1 id's nextTo {
//return True
// Else
return regionId1==nextToReg2 || regionId2==nextToReg1;
}
}
ArrayList<StylistArray>stylistsArr=new ArrayList<StylistArray>();
stylistsArr.add(new StylistArray("BqYWKWzs4r8SyGQvyqH2","18:30"));
stylistsArr.add(new StylistArray("at5kjx5FqIxbnMys8w4q","18:30"));
stylistsArr.add(new StylistArray("nFI5hxfIePx240dmqR0R","18:00"));
stylistsArr.add(new StylistArray("spxSj8UZem5uD0wL46EP","18:20"));
.
https://us-central.jshshskajshdala.net?dasa="+"2018-09-04"+"&ewsss="+"17:50"+"&stylist="+String.valueOf(stylistsArr)
I want to pass this arrayList along with the url. When I try to pass the array values the name of the model class is passing instead of values in the class
Example
I want to pass values like this:
[
{
"stylist": "BqYWKWzs4r8SyGQvyqH2",
"endTime": "18:30"
},
{
"stylist": "at5kjx5FqIxbnMys8w4q",
"endTime": "18:30"
},
{
"stylist": "nFI5hxfIePx240dmqR0R",
"endTime": "18:00"
},
{
"stylist": "spxSj8UZem5uD0wL46EP",
"endTime": "18:00"
}
]
Like #Mathan and #Cris say, you can simply using for looping to create your JSON string. For the following simple pojo:
public class StylistArray {
// use a final so the value can't be change once the object is created.
private final String stylist;
private final String endTime;
public StylistArray(String stylist, String endTime) {
this.stylist = stylist;
this.endTime = endTime;
}
public String getStylist() {
return stylist;
}
public String getEndTime() {
return endTime;
}
}
You can simply doing the following:
List<StylistArray> list = new ArrayList<>();
// assume you have add all items to the list.
JSONArray jsonArray = new JSONArray();
try {
// You need to use simple for loop instead the following foreach
// because foreach is slower than traditional loop.
for (StylistArray stylistArray : list) {
// create JSON object for each item
JSONObject jsonObject = new JSONObject();
jsonObject.put("stylist", stylistArray.getStylist());
jsonObject.put("endTime", stylistArray.getEndTime());
// append it to your JSON array.
jsonArray.put(jsonObject);
}
} catch (JSONException e) {
e.printStackTrace();
// Error happens, try to handle it.
}
Then you can get the string from the JSONArray. I'll let you to find out ;)
Add the Gson dependency in gradle
implementation 'com.google.code.gson:gson:2.8.4'
and rebuild your project
String json= new Gson().toJson(stylistsArr);
Now your "json" variable will have a json array.
Here is the code
List<Map<String, String>> values = new ArrayList<Map<String, String>>();
Map<String, String> maps = new HashMap<>();
maps.put("stylist", "BqYWKWzs4r8SyGQvyqH2");
maps.put("endTime", "18:30");
values.add(maps);
maps.put("stylist", "at5kjx5FqIxbnMys8w4q");
maps.put("endTime", "18:30");
values.add(maps);
maps.put("stylist", "nFI5hxfIePx240dmqR0R");
maps.put("endTime", "18:00");
values.add(maps);
JSONArray mJSONArray = new JSONArray(values);
So I have an object with some fields...
protected String name;
protected String relativePathAndFileName;
protected DateTime next_Run;
protected ArrayList<String> hosts;
Which gets serialized to JSON like this:
public void serialize(){
Gson gson = Converters.registerDateTime(new GsonBuilder()).setPrettyPrinting().create();
String json = gson.toJson(this);
try {
FileWriter writer = new FileWriter(this.relativePathAndFileName);
writer.write (json);
writer.close();
} catch (IOException e) {
logger.error("Error while trying to write myAlert to json: ", e);
}
}
Later when I need to read in this json file, I try to do so like this:
try {
for (File f : alertConfigFiles) {
Gson gson = new Gson();
JsonReader reader = new JsonReader(new FileReader(f));
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> myMap = gson.fromJson(reader, type);
Alert tempAlert = new Alert(myMap);
myAlerts.add(tempAlert);
logger.debug("Imported: " + f.toString());
}
The error that I'm getting is:
Unhandled exception when trying to import config files:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY at line 28 column 13 path $.
The JSON inside the file is something to the effect of:
{
"name": "Logs Per Host - past 24 hours",
"relativePathAndFileName": "./Elk-Reporting/Alerts/logs_per_host24h.json",
"next_Run": "2017-06-07T22:24:56.682-04:00",
"hosts": [
"app-12c",
"app1-18",
"wp-01",
"app-02",
"wp-02",
"cent-04",
"app-06",
"app-05"
]
}
It seems to be choking when it tries to import the ArrayList of hosts, but it was able to write them out without issues.
Can anyone offer some advice on how to get my import working without issues?
try to keep it simple. Using maps and so on, is a way to have issues.
Here is a working code to deserialise / serialise :
package com.rizze.beans.labs.sof;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.google.gson.Gson;
public class SOFGson {
public String json = "{ \"name\": \"Logs Per Host - past 24 hours\", \"relativePathAndFileName\": \"./Elk-Reporting/Alerts/logs_per_host24h.json\", \"next_Run\": \"2017-06-07T22:24:56.682-04:00\", \"hosts\": [ \"bos-qa-app-12c\", \"bos-qa-app1-18\", \"bos-qa-wp-01\", \"bos-lt-app-02\", \"bos-qa-wp-02\", \"bos-dev-cent-04.americanwell.com\", \"bos-qa-app-06\", \"bos-qa-app-05\" ]}";
public class MyObj{
protected String name;
protected String relativePathAndFileName;
protected String next_Run;
protected String[] hosts;
}
#Test
public void test() {
Gson gson = new Gson();
MyObj obj = gson.fromJson(json, MyObj.class);
assertTrue(obj!=null);
assertTrue(obj.hosts.length==8);
System.out.println(gson.toJson(obj));
}
}
here is the class in gist : https://gist.github.com/jeorfevre/7b32a96d4ddc4af68e40bf95f63f2c26
Those two lines seem to be the problem:
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> myMap = gson.fromJson(reader, type);
You serialize your object of some specific class. You then deserialize it to type. But your JSON does not fit into a Map. Better do it like this, so you can use your own class.
YourClass myMap = gson.fromJson(reader, YourClass.class);
If you want to use this approach, you might want to change your Java class to hold an array of strings instead of an ArrayList of strings.
Maybe this page helps you a bit. Especially the first case fits your situation.
Another option is a custom Deserialzer as described here.
I have a JsonObject named "mapping" with the following content:
{
"client": "127.0.0.1",
"servers": [
"8.8.8.8",
"8.8.4.4",
"156.154.70.1",
"156.154.71.1"
]
}
I know I can get the array "servers" with:
mapping.get("servers").getAsJsonArray()
And now I want to parse that JsonArray into a java.util.List...
What is the easiest way to do this?
Definitely the easiest way to do that is using Gson's default parsing function fromJson().
There is an implementation of this function suitable for when you need to deserialize into any ParameterizedType (e.g., any List), which is fromJson(JsonElement json, Type typeOfT).
In your case, you just need to get the Type of a List<String> and then parse the JSON array into that Type, like this:
import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;
JsonElement yourJson = mapping.get("servers");
Type listType = new TypeToken<List<String>>() {}.getType();
List<String> yourList = new Gson().fromJson(yourJson, listType);
In your case yourJson is a JsonElement, but it could also be a String, any Reader or a JsonReader.
You may want to take a look at Gson API documentation.
Below code is using com.google.gson.JsonArray.
I have printed the number of element in list as well as the elements in List
import java.util.ArrayList;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class Test {
static String str = "{ "+
"\"client\":\"127.0.0.1\"," +
"\"servers\":[" +
" \"8.8.8.8\"," +
" \"8.8.4.4\"," +
" \"156.154.70.1\"," +
" \"156.154.71.1\" " +
" ]" +
"}";
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
JsonParser jsonParser = new JsonParser();
JsonObject jo = (JsonObject)jsonParser.parse(str);
JsonArray jsonArr = jo.getAsJsonArray("servers");
//jsonArr.
Gson googleJson = new Gson();
ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class);
System.out.println("List size is : "+jsonObjList.size());
System.out.println("List Elements are : "+jsonObjList.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
OUTPUT
List size is : 4
List Elements are : [8.8.8.8, 8.8.4.4, 156.154.70.1, 156.154.71.1]
I read solution from official website of Gson at here
And this code for you:
String json = "{"client":"127.0.0.1","servers":["8.8.8.8","8.8.4.4","156.154.70.1","156.154.71.1"]}";
JsonObject jsonObject = new Gson().fromJson(json, JsonObject.class);
JsonArray jsonArray = jsonObject.getAsJsonArray("servers");
String[] arrName = new Gson().fromJson(jsonArray, String[].class);
List<String> lstName = new ArrayList<>();
lstName = Arrays.asList(arrName);
for (String str : lstName) {
System.out.println(str);
}
Result show on monitor:
8.8.8.8
8.8.4.4
156.154.70.1
156.154.71.1
I was able to get the list mapping to work with just using #SerializedName for all fields.. no logic around Type was necessary.
Running the code - in step #4 below - through the debugger, I am able to observe that the List<ContentImage> mGalleryImages object populated with the JSON data
Here's an example:
1. The JSON
{
"name": "Some House",
"gallery": [
{
"description": "Nice 300sqft. den.jpg",
"photo_url": "image/den.jpg"
},
{
"description": "Floor Plan",
"photo_url": "image/floor_plan.jpg"
}
]
}
2. Java class with the List
public class FocusArea {
#SerializedName("name")
private String mName;
#SerializedName("gallery")
private List<ContentImage> mGalleryImages;
}
3. Java class for the List items
public class ContentImage {
#SerializedName("description")
private String mDescription;
#SerializedName("photo_url")
private String mPhotoUrl;
// getters/setters ..
}
4. The Java code that processes the JSON
for (String key : focusAreaKeys) {
JsonElement sectionElement = sectionsJsonObject.get(key);
FocusArea focusArea = gson.fromJson(sectionElement, FocusArea.class);
}
Kotlin Extension
for Kotlin developers you can use this extension
inline fun <reified T> String.convertToListObject(): List<T>? {
val listType: Type = object : TypeToken<List<T?>?>() {}.type
return Gson().fromJson<List<T>>(this, listType)
}
Given you start with mapping.get("servers").getAsJsonArray(), if you have access to Guava Streams, you can do the below one-liner:
List<String> servers = Streams.stream(jsonArray.iterator())
.map(je -> je.getAsString())
.collect(Collectors.toList());
Note StreamSupport won't be able to work on JsonElement type, so it is insufficient.