As I indicated in the comment to the question here is the test that shows how to do this:
public class JSONTest {
public static class FullyTypedThing {
public int id;
public String name;
public List<Photos> photos = Lists.newArrayList();
public String username;
public static class Photos {
public String name;
public String url;
}
}
private static final String json = "[ { \"id\" : 33147, \"name\" : \"Refinancing\", \"photos\" : [ {"
+ "\"name\" : \"347.png\", \"url\" : \"/loans/568/photos/092\" } ],"
+ "\"username\" : \"zach1985\"} , { \"id\" : 7693, \"name\" : \"Stuff\","
+ "\"photos\" : [ { \"name\" : \"newpic1.png\", \"url\" : \"/loans/123446/photos/890\" } ],"
+ "\"username\" : \"sengaia\" } ]";
@Test
public void roundtrip() throws IOException {
ObjectMapper mapper = new ObjectMapper();
List<FullyTypedThing> res = Lists.newArrayList(
mapper.readValue(json, FullyTypedThing[].class));
assertEquals(2, res.size());
assertEquals(33147, res.get(0).id);
assertEquals("Refinancing", res.get(0).name);
assertEquals("347.png", res.get(0).photos.get(0).name);
assertEquals("/loans/568/photos/092", res.get(0).photos.get(0).url);
assertEquals(7693, res.get(1).id);
assertEquals("Stuff", res.get(1).name);
assertEquals("newpic1.png", res.get(1).photos.get(0).name);
assertEquals("/loans/123446/photos/890", res.get(1).photos.get(0).url);
assertEquals("[{\"id\":33147,\"name\":\"Refinancing\",\"photos\":"
+ "[{\"name\":\"347.png\",\"url\":\"/loans/568/photos/092\"}],"
+ "\"username\":\"zach1985\"},{\"id\":7693,\"name\":\"Stuff\","
+ "\"photos\":[{\"name\":\"newpic1.png\",\"url\":\"/loans/123446/photos/890\"}],"
+ "\"username\":\"sengaia\"}]", mapper.writeValueAsString(res));
}
}
Answer from Oleg Sklyar on Stack OverflowHow to Deserialize Array of JSON Objects in Java - Stack Overflow
Help deserializing a JSON array of arrays in DSL-JSON
java - How to use Jackson to deserialise an array of objects - Stack Overflow
java - How to deserialize array into an object? - Stack Overflow
This may help you:
import java.io.IOException;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Test {
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
String json = "[\r\n" + " {\r\n" + " \"example\": \"test\",\r\n" + " \"is_valid\": true\r\n"
+ " },\r\n" + " {\r\n" + " \"example\": \"test2\",\r\n" + " \"is_valid\": true\r\n"
+ " }\r\n" + "]";
Example[] ex = mapper.readValue(json, Example[].class);
}
}
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({ "example", "is_valid" })
class Example {
@JsonProperty("example")
private String example;
@JsonProperty("is_valid")
private Boolean isValid;
public String getExample() {
return example;
}
@JsonProperty("example")
public void setExample(String example) {
this.example = example;
}
@JsonProperty("is_valid")
public Boolean getIsValid() {
return isValid;
}
@JsonProperty("is_valid")
public void setIsValid(Boolean isValid) {
this.isValid = isValid;
}
}
When response is a JSON Object you can use default bean deserialiser. In case it is a JSON Array you can read it as array and create response object manually. Below you can find example custom deserialiser and BeanDeserializerModifier which is used to register custom deserialiser. BeanDeserializerModifier allows to use default deserialiser when JSON payload fits POJO model:
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.DeserializationConfig;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.BeanDeserializer;
import com.fasterxml.jackson.databind.deser.BeanDeserializerBase;
import com.fasterxml.jackson.databind.deser.BeanDeserializerModifier;
import com.fasterxml.jackson.databind.exc.MismatchedInputException;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.type.CollectionType;
import java.io.File;
import java.io.IOException;
import java.util.List;
public class JsonApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
SimpleModule module = new SimpleModule();
module.setDeserializerModifier(new BeanDeserializerModifier() {
@Override
public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config, BeanDescription beanDesc, JsonDeserializer<?> deserializer) {
if (beanDesc.getBeanClass() == Response.class) {
return new ResponseJsonDeserializer((BeanDeserializerBase) deserializer);
}
return super.modifyDeserializer(config, beanDesc, deserializer);
}
});
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(module);
System.out.println(mapper.readValue(jsonFile, Response.class));
}
}
class ResponseJsonDeserializer extends BeanDeserializer {
private final BeanDeserializerBase baseDeserializer;
protected ResponseJsonDeserializer(BeanDeserializerBase src) {
super(src);
this.baseDeserializer = src;
}
@Override
public Response deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
if (p.currentToken() == JsonToken.START_OBJECT) {
return (Response) baseDeserializer.deserialize(p, ctxt);
}
if (p.currentToken() == JsonToken.START_ARRAY) {
CollectionType collectionType = ctxt.getTypeFactory().constructCollectionType(List.class, Item.class);
JsonDeserializer<Object> deserializer = ctxt.findRootValueDeserializer(collectionType);
List<Item> results = (List<Item>) deserializer.deserialize(p, ctxt);
Response response = new Response();
response.setCount(results.size());
response.setResults(results);
return response;
}
throw MismatchedInputException.from(p, Response.class, "Only object or array!");
}
}
class Response {
private int count;
private List<Item> results;
// getters, setters, toString
}
class Item {
private String example;
@JsonProperty("is_valid")
private boolean isValid;
// getters, setters, toString
}
Above code for JSON Object payload prints:
Response{count=5, results=[Item{example='test', isValid=true}, Item{example='test2', isValid=true}]}
And for JSON Array payload prints:
Response{count=2, results=[Item{example='test', isValid=true}, Item{example='test2', isValid=true}]}
I want to deserialize this data:
[[ 1, 1, "Neil Peart", 67, "189 Carlton Street", "M5A 2K7", 21.12 ], [ 2, 2, "Geddy Lee", 67, "189 Carlton Street", "M5A 2K7", -21.12 ], [ 3, 3, "Alex Lifeson", 67, "189 Carlton Street", "M5A 2K7", 211.2 ]]
When I use this:
ObjectMapper mapper = new ObjectMapper(); byte[] input = jsonString.getBytes( StandardCharsets.US_ASCII ); com.google.gson.JsonObject dslObject1 = mapper.readValue( jsonString, com.google.gson.JsonObject.class );
It throws a JsonProcessingException with the message:
Cannot deserialize value of type `com.google.gson.JsonObject` from Array value (token `JsonToken.START_ARRAY`)
at [Source: (String)"[[1,1,"Neil Peart",67,"189 Carlton Street","M5A 2K7",21.12]...
When I use this:
byte[] input = jsonString.getBytes( StandardCharsets.US_ASCII ); com.dslplatform.json.JsonObject dslObject2 = dslJson.deserialize( com.dslplatform.json.JsonObject.class, input, input.length );`
it throws an IOException with this message:
Unable to find reader for provided type: interface com.dslplatform.json.JsonObject and fallback serialization is not registered.
Any suggestions?
First create a mapper :
import com.fasterxml.jackson.databind.ObjectMapper;// in play 2.3
ObjectMapper mapper = new ObjectMapper();
As Array:
MyClass[] myObjects = mapper.readValue(json, MyClass[].class);
As List:
List<MyClass> myObjects = mapper.readValue(jsonInput, new TypeReference<List<MyClass>>(){});
Another way to specify the List type:
List<MyClass> myObjects = mapper.readValue(jsonInput, mapper.getTypeFactory().constructCollectionType(List.class, MyClass.class));
From Eugene Tskhovrebov
List<MyClass> myObjects = Arrays.asList(mapper.readValue(json, MyClass[].class))
This solution seems to be the best for me.
Jackson, by default, attempts to deserialize JSON array values into either Java array types or Collection types (eg. ArrayList). But you're trying to make it deserialize a JSON array like [600,200] into a AdDimension object. This won't work out of the box.
You can change your JSON like other answers have suggested or you use a custom deserialization strategy.
Your first option is to define a custom JsonDeserializer (though you should use its sublcass StdDeserializer)
class AdDimensionDeserializer extends JsonDeserializer<AdDimension> {
@Override
public AdDimension deserialize(JsonParser parser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
// you have complete control over the tokens in the JSON, so validate as you wish
ArrayNode arrayNode = parser.readValueAsTree();
return new AdDimension(arrayNode.get(0).asInt(), arrayNode.get(1).asInt());
}
}
and register it as
@JsonDeserialize(using = AdDimensionDeserializer.class)
class AdDimension {
Jackson will instantiate AdDimensionDeserializer and use the instance to deserialize the JSON array elements into an instance(s) of AdDimension.
Another option is to use @JsonCreater
Marker annotation that can be used to define constructors and factory methods as one to use for instantiating new instances of the associated class.
For example
@JsonCreator
public AdDimension(int[] dimensions) {
// again, validate as required
this.width = dimensions[0];
this.height = dimensions[1];
}
Jackson will find this constructor and use it to deserialize your JSON. It will first attempt to deserialize the text [300,250] into a int[], which it obviously can, and then pass that to your constructor.
Maybe is a bad json format??
I think it should be like this
[
{
"id": 1,
"targetedCountries": ["CA", "IT"],
"targetedDomain": "apple.com",
"adDimensions": [{"width":300, "height":250}, {"width":600, "height":200}]
}
]
I can´t test it now, but it seems to be no OK.
The example Java data structure in the original question does not match the description of the JSON structure in the comment.
The JSON is described as
"an array of {object with an array of {object}}".
In terms of the types described in the question, the JSON translated into a Java data structure that would match the JSON structure for easy deserialization with Gson is
"an array of {TypeDTO object with an array of {ItemDTO object}}".
But the Java data structure provided in the question is not this. Instead it's
"an array of {TypeDTO object with an array of an array of {ItemDTO object}}".
A two-dimensional array != a single-dimensional array.
This first example demonstrates using Gson to simply deserialize and serialize a JSON structure that is "an array of {object with an array of {object}}".
input.json Contents:
[
{
"id":1,
"name":"name1",
"items":
[
{"id":2,"name":"name2","valid":true},
{"id":3,"name":"name3","valid":false},
{"id":4,"name":"name4","valid":true}
]
},
{
"id":5,
"name":"name5",
"items":
[
{"id":6,"name":"name6","valid":true},
{"id":7,"name":"name7","valid":false}
]
},
{
"id":8,
"name":"name8",
"items":
[
{"id":9,"name":"name9","valid":true},
{"id":10,"name":"name10","valid":false},
{"id":11,"name":"name11","valid":false},
{"id":12,"name":"name12","valid":true}
]
}
]
Foo.java:
import java.io.FileReader;
import java.util.ArrayList;
import com.google.gson.Gson;
public class Foo
{
public static void main(String[] args) throws Exception
{
Gson gson = new Gson();
TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
System.out.println(gson.toJson(myTypes));
}
}
class TypeDTO
{
int id;
String name;
ArrayList<ItemDTO> items;
}
class ItemDTO
{
int id;
String name;
Boolean valid;
}
This second example uses instead a JSON structure that is actually "an array of {TypeDTO object with an array of an array of {ItemDTO object}}" to match the originally provided Java data structure.
input.json Contents:
[
{
"id":1,
"name":"name1",
"items":
[
[
{"id":2,"name":"name2","valid":true},
{"id":3,"name":"name3","valid":false}
],
[
{"id":4,"name":"name4","valid":true}
]
]
},
{
"id":5,
"name":"name5",
"items":
[
[
{"id":6,"name":"name6","valid":true}
],
[
{"id":7,"name":"name7","valid":false}
]
]
},
{
"id":8,
"name":"name8",
"items":
[
[
{"id":9,"name":"name9","valid":true},
{"id":10,"name":"name10","valid":false}
],
[
{"id":11,"name":"name11","valid":false},
{"id":12,"name":"name12","valid":true}
]
]
}
]
Foo.java:
import java.io.FileReader;
import java.util.ArrayList;
import com.google.gson.Gson;
public class Foo
{
public static void main(String[] args) throws Exception
{
Gson gson = new Gson();
TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
System.out.println(gson.toJson(myTypes));
}
}
class TypeDTO
{
int id;
String name;
ArrayList<ItemDTO> items[];
}
class ItemDTO
{
int id;
String name;
Boolean valid;
}
Regarding the remaining two questions:
is Gson extremely fast?
Not compared to other deserialization/serialization APIs. Gson has traditionally been amongst the slowest. The current and next releases of Gson reportedly include significant performance improvements, though I haven't looked for the latest performance test data to support those claims.
That said, if Gson is fast enough for your needs, then since it makes JSON deserialization so easy, it probably makes sense to use it. If better performance is required, then Jackson might be a better choice to use. It offers much (maybe even all) of the conveniences of Gson.
Or am I better to stick with what I've got working already?
I wouldn't. I would most always rather have one simple line of code like
TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
...to easily deserialize into a complex data structure, than the thirty lines of code that would otherwise be needed to map the pieces together one component at a time.
Use your bean class like this, if your JSON data starts with an an array object. it helps you.
Users[] bean = gson.fromJson(response,Users[].class);
Users is my bean class.
Response is my JSON data.
Try this:
desrializaedClubs = (ArrayList<FootballClubNL>)in.readObject();
You serialized a List but you are deserializing to FootballClubNL. Just change this line
FootballClubNL club = (FootballClubNL)in.readObject();
to
desrializaedClubs = (ArrayList<FootballClubNL>)in.readObject();