Json to collection java

Convert JSON Array to List using Gson in Java

In this quick tutorial, you’ll learn how to use the Gson library to convert a JSON array string into a list of Java Objects and vice versa.

implementation 'com.google.code.gson:gson:2.8.6' 
dependency> groupId>com.google.code.gsongroupId> artifactId>gsonartifactId> version>2.8.6version> dependency> 
[  "name": "John Doe", "email": "john.doe@example.com", "roles": [ "Member", "Admin" ], "admin": true >,  "name": "Tom Lee", "email": "tom.lee@example.com", "roles": [ "Member" ], "admin": false > ] 

To convert the above JSON array to a list of Java Objects, let us first create a simple User class to map JSON fields:

public class User  public String name; public String email; private String[] roles; private boolean admin; public User()  > public User(String name, String email, String[] roles, boolean admin)  this.name = name; this.email = email; this.roles = roles; this.admin = admin; > // getters and setters, toString() . (omitted for brevity) > 

Now we can use the fromJson() method from the Gson class to convert the above JSON array to a list of User objects:

try  // JSON array String json = "[ + "\"roles\":[\"Member\",\"Admin\"],\"admin\":true>, + "\"email\":\"tom.lee@example.com\",\"roles\":[\"Member\"],\"admin\":false>]"; // convert JSON array to Java List ListUser> users = new Gson().fromJson(json, new TypeTokenListUser>>() >.getType()); // print list of users users.forEach(System.out::println); > catch (Exception ex)  ex.printStackTrace(); > 
Username='John Doe', email='john.doe@example.com', roles=[Member, Admin], admin=true> Username='Tom Lee', email='tom.lee@example.com', roles=[Member], admin=false> 
User[] users = new Gson().fromJson(json, User[].class); 

If your JSON array is stored in a JSON file, you can still read and parse its content to a list of Java Objects using Gson, as shown below:

ListUser> users = new Gson().fromJson(new FileReader("users.json"), new TypeTokenListUser>>() >.getType()); 

The following example demonstrates how to use the toJson() method from the Gson class to convert a list of Java Objects to their JSON representation:

try  // create a list of users ListUser> users = Arrays.asList( new User("John Doe", "john.doe@example.com", new String[]"Member", "Admin">, true), new User("Tom Lee", "tom.lee@example.com", new String[]"Member">, false) ); // convert users list to JSON array String json = new Gson().toJson(users); // print JSON string System.out.println(json); > catch (Exception ex)  ex.printStackTrace(); > 
["name":"John Doe","email":"john.doe@example.com","roles":["Member","Admin"],"admin":true>, "name":"Tom Lee","email":"tom.lee@example.com","roles":["Member"],"admin":false>] 

To write a list of Java Objects directly to a JSON file, you can pass an instance of Writer to the toJson() method:

try  // create a list of users ListUser> users = Arrays.asList( new User("John Doe", "john.doe@example.com", new String[]"Member", "Admin">, true), new User("Tom Lee", "tom.lee@example.com", new String[]"Member">, false) ); // create writer Writer writer = new FileWriter("users.json"); // convert users list to JSON file new Gson().toJson(users, writer); // close writer writer.close(); > catch (Exception ex)  ex.printStackTrace(); > 

For more Gson examples, check out the How to read and write JSON using Gson in Java tutorial. ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

Jackson – Unmarshall to Collection/Array

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

We’re looking for a new Java technical editor to help review new articles for the site.

1. Overview

This tutorial will show how to deserialize a JSON Array to a Java Array or Collection with Jackson 2.

If you want to dig deeper and learn other cool things you can do with the Jackson 2 – head on over to the main Jackson tutorial.

2. Unmarshall to Array

Jackson can easily deserialize to a Java Array:

@Test public void givenJsonArray_whenDeserializingAsArray_thenCorrect() throws JsonParseException, JsonMappingException, IOException < ObjectMapper mapper = new ObjectMapper(); ListlistOfDtos = Lists.newArrayList( new MyDto("a", 1, true), new MyDto("bc", 3, false)); String jsonArray = mapper.writeValueAsString(listOfDtos); // [, // ] MyDto[] asArray = mapper.readValue(jsonArray, MyDto[].class); assertThat(asArray[0], instanceOf(MyDto.class)); >

3. Unmarshall to Collection

Reading the same JSON Array into a Java Collection is a bit more difficult – by default, Jackson will not be able to get the full generic type information and will instead create a collection of LinkedHashMap instances:

@Test public void givenJsonArray_whenDeserializingAsListWithNoTypeInfo_thenNotCorrect() throws JsonParseException, JsonMappingException, IOException < ObjectMapper mapper = new ObjectMapper(); ListlistOfDtos = Lists.newArrayList( new MyDto("a", 1, true), new MyDto("bc", 3, false)); String jsonArray = mapper.writeValueAsString(listOfDtos); List asList = mapper.readValue(jsonArray, List.class); assertThat((Object) asList.get(0), instanceOf(LinkedHashMap.class)); >

There are two ways to help Jackson understand the right type information – we can either use the TypeReference provided by the library for this very purpose:

@Test public void givenJsonArray_whenDeserializingAsListWithTypeReferenceHelp_thenCorrect() throws JsonParseException, JsonMappingException, IOException < ObjectMapper mapper = new ObjectMapper(); ListlistOfDtos = Lists.newArrayList( new MyDto("a", 1, true), new MyDto("bc", 3, false)); String jsonArray = mapper.writeValueAsString(listOfDtos); List asList = mapper.readValue( jsonArray, new TypeReference() < >); assertThat(asList.get(0), instanceOf(MyDto.class)); >

Or we can use the overloaded readValue method that accepts a JavaType:

@Test public void givenJsonArray_whenDeserializingAsListWithJavaTypeHelp_thenCorrect() throws JsonParseException, JsonMappingException, IOException < ObjectMapper mapper = new ObjectMapper(); ListlistOfDtos = Lists.newArrayList( new MyDto("a", 1, true), new MyDto("bc", 3, false)); String jsonArray = mapper.writeValueAsString(listOfDtos); CollectionType javaType = mapper.getTypeFactory() .constructCollectionType(List.class, MyDto.class); List asList = mapper.readValue(jsonArray, javaType); assertThat(asList.get(0), instanceOf(MyDto.class)); >

One final note is that the MyDto class needs to have the no-args default constructor – if it doesn’t, Jackson will not be able to instantiate it:

com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class org.baeldung.jackson.ignore.MyDto]: can not instantiate from JSON object (need to add/enable type information?)

4. Conclusion

Mapping JSON arrays to java collections is one of the more common tasks that Jackson is used for, and these solutions are vital to getting to a correct, type-safe mapping.

The implementation of all these examples and code snippets can be found in our GitHub project – this is a Maven-based project, so it should be easy to import and run as it is.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

Java Language JSON in Java Deserialize JSON collection to collection of Objects using Jackson

And you want to parse it into a JSON array or a map of Person objects. Due to type erasure you cannot construct classes of List and Map at runtime directly (and thus use them to deserialize JSON). To overcome this limitation jackson provides two approaches — TypeFactory and TypeReference .

TypeFactory

The approach taken here is to use a factory (and its static utility function) to build your type for you. The parameters it takes are the collection you want to use (list, set, etc.) and the class you want to store in that collection.

TypeReference

The type reference approach seems simpler because it saves you a bit of typing and looks cleaner. TypeReference accepts a type parameter, where you pass the desired type List . You simply instantiate this TypeReference object and use it as your type container.

Now let’s look at how to actually deserialize your JSON into a Java object. If your JSON is formatted as an array, you can deserialize it as a List. If there is a more complex nested structure, you will want to deserialize to a Map. We will look at examples of both.

Deserializing JSON array

TypeFactory approach

CollectionType listType = factory.constructCollectionType(List.class, Person.class); List list = mapper.readValue(jsonString, listType); 

TypeReference approach

TypeReference listType = new TypeReference() <>; List list = mapper.readValue(jsonString, listType); 

Deserializing JSON map

TypeFactory approach

CollectionType mapType = factory.constructMapLikeType(Map.class, String.class, Person.class); List list = mapper.readValue(jsonString, mapType); 

TypeReference approach

TypeReference mapType = new TypeReference>() <>; Map list = mapper.readValue(jsonString, mapType); 

Details

import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.type.CollectionType; 
ObjectMapper mapper = new ObjectMapper(); TypeFactory factory = mapper.getTypeFactory(); 

Note

While TypeReference approach may look better it has several drawbacks:

  1. TypeReference should be instantiated using anonymous class
  2. You should provide generic explicity

Failing to do so may lead to loss of generic type argument which will lead to deserialization failure.

pdf

PDF — Download Java Language for free

Источник

Читайте также:  Django запуск скрипта python
Оцените статью