JSON to List<T> [duplicate] - java

This question already has answers here:
How to convert JSON string into List of Java object?
(10 answers)
Why can't I unwrap the root node and deserialize an array of objects?
(3 answers)
Closed 5 years ago.
im new here and have a problem, surprise surprise :D
I have a JSON String and i want to convert it into a List.
My JSON String:
{
"results": [
{
"uri": "http://xxxxxx",
"downloadCount": 0,
"lastDownloaded": "2017-04-10T16:12:47.438+02:00",
"remoteDownloadCount": 0,
"remoteLastDownloaded": "1970-01-01T01:00:00.000+01:00"
},
{
"uri": "http://yyyyyyy",
"downloadCount": 0,
"lastDownloaded": "2017-04-10T16:12:47.560+02:00",
"remoteDownloadCount": 0,
"remoteLastDownloaded": "1970-01-01T01:00:00.000+01:00"
},]}
How can i convert it in Java?
EDIT:
My Problem was the "results" Root-Element...
this
worked fine.

First you need to make a Java model object which matches the model in your JSON e.g.:
public class MyClass {
private String uri;
private int downloadCount;
private ZonedDateTime lastDownloaded;
private int remoteDownloadCount;
private ZonedDateTime remoteLastDownloaded;
(getters and setters)
}
Then you can use a JSON parser like Jackson (https://github.com/FasterXML/jackson) to parse your JSON as a list of instances of this object using the Jackson ObjectMapper class (https://fasterxml.github.io/jackson-databind/javadoc/2.7/com/fasterxml/jackson/databind/ObjectMapper.html):
ObjectMapper objectMapper = new ObjectMapper();
MyClass[] myClasses = objectMapper.readValue(jsonString, MyClass[].class);

Create a class for accessing data.
class ListElement {
public String uri;
public int downloadCount;
public String lastDownloaded;
public int remoteDownloadCount;
public String remoteLastDownloaded;
}
Then, parse the json and get the list and convert it to list.
public static void main(String[] args) throws ParseException {
Gson gson = new Gson();
JsonElement list = new JsonParser().parse(json).getAsJsonObject().get("results");
List<ListElement> listObj = gson.fromJson(list, new TypeToken<List<ListElement>>() {}.getType());
System.out.println(listObj.size());
}
Note that I used String instead of ZonedDateTime. Since, its a String(enclosed between quotes) for JsonObject.

Related

How to serialize an object to a list of one elements with gson

I have some json string like this:
example1
{
"path":{
"start":"abc"
},
"name":"Fork1"
}
example2
{
"path":[{
"start":"abc"
},
{
"start":"def"
}],
"name":"Fork1"
}
and I want to serialize with one JAVA object like this:
#Data
public static class ForkNode {
private List<Path> path;
private String name;
}
#Data
public static class Path {
private String start;
}
new Gson().fromJson(jsonStr, ForkNode.class)
but it will throw an exception
IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 2 column 11 path $.path
So how do I treat the first example as a list of one elements?
Or is there any way I can serialize two different types of json strings with one object?
I don't think it is a good way to serialize two different types of json strings with ONE object.
For example 1, the Object should be like this:
#Data
public static class ForkNode {
// only one path
private Path path;
private String name;
}
#Data
public static class Path {
private String start;
}
new Gson().fromJson(jsonStr, ForkNode.class)
While For example 2, the Object should be like this:
#Data
public static class ForkNode {
// several paths
private List<Path> path;
private String name;
}
#Data
public static class Path {
private String start;
}
new Gson().fromJson(jsonStr, ForkNode.class)
In JSON:
Objects are enclosed directly in curly brackets {} While JSON
Arrays that are enclosed in square brackets [] inside JSON Objects.
One more thing, If you do really want to do that, I think you need to implement a custom deserializer by yourself. Please ref the doc of Gson.
I solved it by modify JsonObject.
I use this code to convent JsonObject to JsonArray, so I can deserializer it like JsonArray.
public void objectToArray(JsonObject jsonObject, String node) {
JsonElement jsonElement = jsonObject.get(node);
if (jsonElement instanceof JsonObject) {
JsonArray array = new JsonArray();
array.add(jsonElement);
jsonObject.remove(node);
jsonObject.add(node, array);
}
}

JSON to a Java collection [duplicate]

This question already has answers here:
How do I convert a JSON array into a Java List. I'm using svenson
(4 answers)
Closed 5 years ago.
I got JSON like
{
"items":[
{
"id":15
,"name":"abc"
}
,{
"id":16
,"name":"xyz%"
}
,{
"id":17
,"name":"qwerty"
}
,{
"id":18
,"name":"rudloph"
}
,{
"id":19
,"name":"jane"
}
,{
"id":20
,"name":"doe"
}
]
}
I have class which is like:
public class Foo {
public String id;
public String name;
}
And I want to convert this JSON into List<Foo>. How can i do this? Right now I am doing like:
List<Foo> fooList = new ArrayList<>();
JSONObject jsonObject = new JSONObject(json);
JSONArray araray = jsonObject.getJSONArray("items");
for(int i =0 ; i < araray.length();i++){
Foo dto = new Foo();
dto.setId(Long.valueOf((String) araray.getJSONObject(i).get("id")));
dto.setName((String) araray.getJSONObject(i).get("name"));
fooList.add(dto);
}
PS: Cannot change JSON. Jackson or Gson. Please let me know with code example.
i think you need to use the java json api and you need bind it manually
If you use gson, you may use TypeToken to load the json string into a custom Foo object.
List<Foo> objects = gson.fromJson(source, new TypeToken<List<Foo>>(){}.getType());
source can be String or BufferedReader.
You are having the wrong model for the JSON String. actually the list of Foo is inside another Model. Simply write another class like
public class Item {
List<Foo> items;
public Item() {
}
// getter setter
}
Now you can use com.fasterxml.jackson.databind.ObjectMapper like this
ObjectMapper mapper = new ObjectMapper();
Item item = mapper.readValue(json, Item.class);
for(Foo foo : item.getItems()) {
...
}
Try this with GSON.
Gson gson = new Gson();
Map<String, List<Foo>> objects = gson.fromJson(source,
new TypeToken<Map<String, List<Foo>>>(){}.getType());
List<Foo> list = objects.get("items");

how can I deserialize a non unified json in Java?

I want to send the server an http request with this json (upper line)
and I want to get such a json and parse it to Java object (lower line)
I remember from last times, that a missing field in a collection that I want to deserialize
crashes the deserialization
(for a single deserialization, if the json has no such field - a default value is inserted)
Is there any way I can create a single Java class to represent both the request json and the two types on response json objects?
My try:
public class ConfigValue {
public String key;
public String defaultValue;
public String value;
}
Gson gson = new Gson();
Type collectionType = new TypeToken<Array<ConfigValue>>() {
}.getType();
ConfigValue[] configValues = (ConfigValue[]) gson
.fromJson(result, collectionType);
Neither of the two JSON strings in your image are directly a list (or array) of ConfigValue objects. They are in fact a JSON object, with one property configValues, which is a list of ConfigValue objects. You therefore need a wrapper class to deserialize them to:
public class ConfigValues {
public ConfigValue[] configValues;
}
public class ConfigValue {
public String key;
public String defaultValue;
public String value;
}
public static void main(String[] args) {
String firstJson = "{\"configValues\":[{\"key\":\"radiusMeters\",\"value\":\"200\"}]}";
String secondJson = "{\"configValues\":[{\"key\":\"redeemExpirationMins\",\"defaultValue\":\"300\"},{\"key\":\"radiusMeters\",\"value\":\"200\",\"defaultValue\":\"400\"}]}";
Gson gson = new Gson();
ConfigValues firstConfigValues = gson.fromJson(firstJson, ConfigValues.class);
ConfigValues secondConfigValues = gson.fromJson(secondJson, ConfigValues.class);
System.out.println(firstConfigValues);
System.out.println(secondConfigValues);
}
If you add toString methods to the two classes, the main method prints the following deserialized objects:
ConfigValues(configValues=[ConfigValue(key=radiusMeters, defaultValue=null, value=200)])
ConfigValues(configValues=[ConfigValue(key=redeemExpirationMins, defaultValue=300, value=null), ConfigValue(key=radiusMeters, defaultValue=400, value=200)])
You can see that any missing fields of ConfigValue are deserialized to null.

How to convert JSON string to custom object? [duplicate]

This question already has answers here:
Convert a JSON string to object in Java ME?
(14 answers)
Closed 9 years ago.
I've string like this (just )
"{\"username":\"stack\",\"over":\"flow\"}"
I'd successfully converted this string to JSON with
JSONObject object = new JSONObject("{\"username":\"stack\",\"over":\"flow\"}");
I've a class
public class MyClass
{
public String username;
public String over;
}
How can I convert JSONObject into my custom MyClass object?
you need Gson:
Gson gson = new Gson();
final MyClass myClass = gson.fromJson(jsonString, MyClass.class);
also what might come handy in future projects for you:
Json2Pojo Class generator
You can implement a static method in MyClass that takes JSONObject as a parameter and returns a MyClass instance. For example:
public static MyClass convertFromJSONToMyClass(JSONObject json) {
if (json == null) {
return null;
}
MyClass result = new MyClass();
result.username = (String) json.get("username");
result.name = (String) json.get("name");
return result;
}

How do I provide the following json output using java

I am trying to generate the following json output using the java net.sf.json libs but have been unsuccessful.
[
{
"data": [
[
1,
1,
"Text"
],
[
2,
2,
"Text"
],
[
3,
0,
"Text"
],
[
5,
2,
"Text"
]
],
"label": "First Series"
}
]
I have read on these forums Gson is my best bet going forward. Can anyone provide an example of how to generate this json using Gson or another suitable java based library.
Thanks in advance
i like this
http://www.json.org/javadoc/org/json/JSONObject.html from http://json.org/java/
and JSONArray.
with those 2 objects:
JSONArray inner = new JSONArray()
inner.add(1);inner.add("text");
JSONObject outer = new JSONObject();
outer.put("data",inner);
outer.put("label", "stuff");
String out = outer.toString()
Gson
Gson is a Java library that can be used to convert Java Objects into its JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.
There are a few open-source projects that can convert Java objects to JSON. However, most of them require that you place Java annotations in your classes something that you can not do if you do not have access to the source-code. Most also do not fully support the use of Java Generics. Gson considers both of these as very important design goals.
import com.google.gson.Gson;
class Person {
private int age = 10;
private String name = "jigar";
}
Person obj = new Person();
Gson gson = new Gson();
String json = gson.toJson(obj);
http://json.org/java/
import org.json.JSONObject;
...
...
JSONObject json = new JSONObject();
json.put("city", "Mumbai");
json.put("country", "India");
...
String output = json.toString();
This is easy enough using a Java object like this:
public class GsonTest {
private List<DataItem> data;
private String label;
public GsonTest() {} // for Gson
public GsonTest(List<DataItem> data, String label) {
this.data = data;
this.label = label;
}
// ...
}
public class DataItem {
private int val1;
private int val2;
private String text;
public DataItem() {} // for Gson
public DataItem(int val1, int val2, String text) {
this.val1 = val1;
this.val2 = val2;
this.text = text;
}
// ...
}
Since your JSON format uses an array rather than an object for each data item (an object would make more sense based on your sample) you need to add a custom handler for serializing and deserializing DataItems to and from JSON arrays.
public class DataItemConverter implements JsonDeserializer<DataItem>,
JsonSerializer<DataItem> {
public DataItem deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
JsonArray array = json.getAsJsonArray();
int val1 = array.get(0).getAsInt();
int val2 = array.get(1).getAsInt();
String text = array.get(2).getAsString();
return new DataItem(val1, val2, text);
}
public JsonElement serialize(DataItem src, Type typeOfSrc,
JsonSerializationContext context) {
JsonArray array = new JsonArray();
array.add(new JsonPrimitive(src.val1));
array.add(new JsonPrimitive(src.val2));
array.add(new JsonPrimitive(src.text));
return array;
}
}
Then you just need to register this converter when you create your Gson instance and you're good to go! Since our DataItem converter handles deserialization as well, you'll be able to deserialize the generated JSON as a List<GsonTest> as well.
public static void testSerialization() {
List<DataItem> data = new ArrayList<DataItem>();
data.add(new DataItem(1, 1, "Text"));
data.add(new DataItem(2, 2, "Text"));
data.add(new DataItem(3, 0, "Text"));
data.add(new DataItem(5, 2, "Text"));
GsonTest test = new GsonTest(data, "First Series");
List<GsonTest> list = new ArrayList<GsonTest>();
list.add(test);
Gson gson = new GsonBuilder()
.registerTypeAdapter(DataItem.class, new DataItemConverter())
.create();
System.out.println(gson.toJson(list));
}

Categories