Java json serialize array

others-How to serialize and deserialize java ArrayList with gson?

In this post, I would demo how to do java ArrayList and JSON conversion by using gson, we would use java template method which has a generic type to do this job.

2. Environment

3. The solution

3.1 The old way

When we want to serialize a List object to json and parse json string to a List, we can do this job using TypeToken .

Читайте также:  Проверка правильности расстановки скобок python

Suppose we have a MyCar object:

class MyCar  String manu; Date bornDate; String type; String description; public static MyCar newCar(String manu, Date borndate, String type, String desc)  MyCar myCar = new MyCar(); myCar.manu = manu; myCar.bornDate = borndate; myCar.type = type; myCar.description = desc; return myCar; > public String getManu()  return manu; > public void setManu(String manu)  this.manu = manu; > public Date getBornDate()  return bornDate; > public void setBornDate(Date bornDate)  this.bornDate = bornDate; > public String getType()  return type; > public void setType(String type)  this.type = type; > public String getDescription()  return description; > public void setDescription(String description)  this.description = description; > > 

If we want to use gson, we should add dependency as follows:

  com.google.code.gson gson 2.2.4  

Then we can define a TypeToken like this:

private static final Type mycarTypeToken = new TypeTokenArrayListEmailTarget>>() <>.getType(); 
public class TypeToken extends Object. Represents a generic type T . Java doesn't yet provide a way to represent generic types, so this class does. Forces clients to create a subclass of this class which enables retrieval the type information even at runtime 

Then we can parse the JSON to List as follows:

public static ListMyCar> getList(String json)  if(json==null) return null; return gson.fromJson(json, mycarTypeToken); > 

We can convert List to JSON as follows:

public static String getJson(List myCarList)  if(myCarList==null) return null; return gson.toJson(myCarList,mycarTypeToken); > 

3.2 The java template method way

We can also do this job more generally by using java template method, which has a to represent any type that would be used in the conversion.

Convert from List to JSON:

public static T> String getSomeJsonString(ListT> someList)  if(someList==null) return null; Type theListType = new TypeTokenArrayListT>>() <>.getType(); return gson.toJson(someList, theListType); > 

Convert from JSON to List:

public static final T> ListT> getListFromJson(ClassT[]> theClass, String json)  T[] jsonToObject = new Gson().fromJson(json, theClass); return Arrays.asList(jsonToObject); > 

Then we can test the code as follows:

 public static void main(String[] args)  ListMyCar> cars = new ArrayList<>(); cars.add(MyCar.newCar("honda",new Date(),"suv","haha ha")); cars.add(MyCar.newCar("audi",new Date(),"cross","askdfjla")); String json = getSomeJsonString(cars); System.out.println(json); ListMyCar> cars2 = getSomeList(json); System.out.println("got cars:"+cars2.size()); > 

Run the above code, We get this:

["manu":"honda","bornDate":"Aug 26, 2021 2:59:22 PM","type":"suv","description":"haha ha">,"manu":"audi","bornDate":"Aug 26, 2021 2:59:22 PM","type":"cross","description":"askdfjla">] got cars:2 Process finished with exit code 0 

4. Summary

In this post, I demonstrated how to serialize and deserialize List from and to JSON string by using gson and java template method.

Источник

Convert /Serialize array of objects to / from json in java (Gson /example)

Program – Convert/ Serialize array of objects to/from json (Gson & example)

1.) Person Class:

  • Person class containing firstName, lastName, age etc.
  • We have overloaded toString method to print person information.
package org.learn.gson; public class Person < public String firstName; public String lastName; public int age; public String contact; public Person(String firstName, String lastName, int age, String contact) < this.firstName = firstName; this.lastName = lastName; this.age = age; this.contact = contact; >public String toString() < return "[" + firstName + " " + lastName + " " + age + " " +contact +"]"; >>

2.) JSONArrayConverter Class:

JSONArrayConverter is responsible for performing following operations.

  1. Convert Person[] array to JSON string
  2. Convert the JSON string to Person[] array
package org.learn.gson; import java.util.Arrays; import java.util.stream.Stream; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class JSONArrayConverter < public static void main( String[] args ) < Gson objGson = new GsonBuilder().setPrettyPrinting().create(); Person[] personList = Stream.of( new Person("Mike", "harvey", 34, "001894536"), new Person("Nick", "young", 75, "005425676"), new Person("Jack", "slater", 21 ,"009654153"), new Person("gary", "hudson", 55,"00564536")) .toArray(Person[]::new); //Array to JSON String mapToJson = objGson.toJson(personList); System.out.println("1. Person array to JSON conversion is : \n"); System.out.println(mapToJson); //JSON to Array Person[] arrayPerson = objGson.fromJson(mapToJson, Person[].class); System.out.println("2. JSON to Array of persons conversion is :\n"); Arrays.stream(arrayPerson).forEach(System.out::println); >>

Download code – Serialize array of objects to/from JSON (GSON)

Output – convert array of objects to/from json (Gson & example)

1. Person array to JSON conversion is : [ < "firstName": "Mike", "lastName": "harvey", "age": 34, "contact": "001894536" >, < "firstName": "Nick", "lastName": "young", "age": 75, "contact": "005425676" >, < "firstName": "Jack", "lastName": "slater", "age": 21, "contact": "009654153" >, < "firstName": "gary", "lastName": "hudson", "age": 55, "contact": "00564536" >] 2. JSON to Array of persons conversion is : [Mike harvey 34 001894536] [Nick young 75 005425676] [Jack slater 21 009654153] [gary hudson 55 00564536]

You may also like:

Источник

Serialize/ convert list of objects to/from json in java (Gson & example)

Program – convert list of objects to/from json in java (GSON & example)

1.) Person Class:

  • Person class containing firstName, lastName, age etc.
  • We have overloaded toString method to print person information.
package org.learn.gson; public class Person < public String firstName; public String lastName; public int age; public String contact; public Person(String firstName, String lastName, int age, String contact) < this.firstName = firstName; this.lastName = lastName; this.age = age; this.contact = contact; >public String toString() < return "[" + firstName + " " + lastName + " " + age + " " +contact +"]"; >>

2.) JSONConverter Class:

JSONConverter is responsible for performing following operations.

package org.learn.gson; import java.lang.reflect.Type; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; public class JSONConverter < public static void main( String[] args ) < Gson objGson = new GsonBuilder().setPrettyPrinting().create(); List personList = Stream.of( new Person("Mike", "harvey", 34, "001894536"), new Person("Nick", "young", 75, "005425676"), new Person("Jack", "slater", 21 ,"009654153"), new Person("gary", "hudson", 55,"00564536"), new Person("Mike", "harvey", 21 ,"003685417"), new Person("gary", "hudson", 25,"00452341")) .collect(Collectors.toList()); //Convert list to json System.out.println("1. Convert list of person objects to Json"); String json = objGson.toJson(personList); System.out.println(json); //Convert json back to list System.out.println("2. Convert JSON to list of person objects"); Type listType = new TypeToken() <>.getType(); List readFromJson = objGson.fromJson(json, listType); readFromJson.forEach(System.out::println); > >

Download Code – convert list of objects to/from json (GSON)

Output – convert list of objects to/from json in java (GSON & example)

1. Convert list of person objects to Json [ < "firstName": "Mike", "lastName": "harvey", "age": 34, "contact": "001894536" >, < "firstName": "Nick", "lastName": "young", "age": 75, "contact": "005425676" >, < "firstName": "Jack", "lastName": "slater", "age": 21, "contact": "009654153" >, < "firstName": "gary", "lastName": "hudson", "age": 55, "contact": "00564536" >, < "firstName": "Mike", "lastName": "harvey", "age": 21, "contact": "003685417" >, < "firstName": "gary", "lastName": "hudson", "age": 25, "contact": "00452341" >] 2. Convert JSON to list of person objects [Mike harvey 34 001894536] [Nick young 75 005425676] [Jack slater 21 009654153] [gary hudson 55 00564536] [Mike harvey 21 003685417] [gary hudson 25 00452341]

You may also like:

Источник

Using Jackson for JSON Serialization and Deserialization

Jackson is one of the most common Java libraries for processing JSON. It is used for reading and writing JSON among other tasks. Using Jackson, you can easily handle automatic conversion from Java objects to JSON and back. In this article, we delve into some common Jackson usage patterns.

2. Converting a POJO to JSON

Suppose we want to convert a sample POJO (Plain Old Java Object) to JSON. An example class is defined below.

public class User < private String firstName; private String lastName; private Date dateOfBirth; private ListemailAddrs; public User(String firstName,String lastName) < this.firstName = firstName; this.lastName = lastName; >// standard getters and setters here >

Converting such an object to JSON is just a couple of lines:

ObjectMapper mapper = new ObjectMapper(); User user = new User(«Harrison», «Ford»); user.setEmailAddrs(Arrays.asList(«harrison@example.com»)); mapper.writeValue(System.out, user); // prints:

3. Pretty Printing

Note that the default output is quite compact. Sometimes it is useful to be able to view indented output for debugging purposes. To produce properly indented output, enable the option SerializationFeature.INDENT_OUTPUT on the ObjectMapper instance before using it to serialize the object.

ObjectMapper mapper = new ObjectMapper(); mapper.enable(SerializationFeature.INDENT_OUTPUT); User user = new User("Harrison", "Ford"); .

The output generated now is nicely indented:

4. Ignore NULL fields

How do we tell Jackson not to serialize null values (as for “ dateOfBirth ” above)? There are a couple of ways. You can tell the ObjectMapper to skip all NULL fields, or you can use annotations to specify per class or per field.

4.1. Configuring ObjectMapper

. mapper.setSerializationInclusion(Include.NON_NULL); User user = new User(«Harrison», «Ford»); . // prints:

4.2. With an Annotation

Use the annotation @JsonInclude(Include.NON_NULL) on the target object class to eliminate serialization of all NULL fields.

@JsonInclude(Include.NON_NULL) public class User

Or on a field (or property) to disable specific NULL fields from being serialized. In the code below, dateOfBirth will be ignored if null, but not heightInM .

. @JsonInclude(Include.NON_NULL) private Date dateOfBirth; private Float heightInM; .

5. Ignore Empty Arrays

When you have a class with an empty array initializer, the value is serialized as an empty JSON array.

class User < . private ListphoneNumbers = new ArrayList<>(); . > // serialized to:

When you want to skip empty array declarations being output, you can use the following.

mapper.setSerializationInclusion(Include.NON_EMPTY);

6. Generate JSON String

How can we generate a JSON string representation instead of writing it directly to a file or an OutputStream? Maybe you want to store the JSON string in a database. Use the writeValueAsString() method.

// set up user String jsonStr = mapper.writeValueAsString(user);

7. Formatting Dates

By default, Jackson prints Date fields as numeric timestamps as shown below:

Calendar c = Calendar.getInstance(); c.clear(); c.set(1942, 6, 13); user.setDateOfBirth(c.getTime()); // prints:

Turning off numeric timestamp results in serialization of a date in the ISO 8601 format as shown below:

. mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); . // prints:

Change the default date format by using SimpleDateFormat as shown:

. DateFormat fmt = new SimpleDateFormat(«dd-MMM-yyyy»); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); . // prints:

8. Converting JSON to POJO

Reading and converting JSON to a Java object is just as easy with Jackson. Accomplished in just a couple of lines:

ObjectMapper mapper = new ObjectMapper(); User user = mapper.readValue(new File(jsonFile), User.class);

The target class (User in this case) needs a no-arguments default constructor defined – failing which you get this exception:

Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of sample.User: no suitable constructor found, can not deserialize from Object value (missing default constructor or creator, or perhaps need to add/enable type information?)

The situation is easily address by adding a no-arguments default constructor.

public class User < private String firstName; private String lastName; private Date dateOfBirth; private ListemailAddrs; public User() <> . >

9. Adjusting Date Format

As before, the date format needs to be adjusted unless it is in ISO 8601 format. Parsing the following JSON fails:

The following exception is reported:

Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not deserialize value of type java.util.Date from String "13-Jul-1942": not a valid representation (error: Failed to parse Date value '13-Jul-1942': Can not parse date "13-Jul-1942": not compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"))

Specify the date format if you are using a non-standard format as shown:

DateFormat fmt = new SimpleDateFormat("dd-MMM-yyyy"); mapper.setDateFormat(fmt);

10. Ignoring Unknown Properties

Sometimes the JSON you are trying to read might include some properties not defined in the Java class. Maybe the JSON was updated but the change is not yet reflected in the Java class. In such cases, you might end up with an exception like this:

Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "gender" (class sample.User), not marked as ignorable (6 known properties: . )

You can tell Jackson to ignore such properties on a global level by disabling a deserialization feature as follows:

mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

Alternatively, you can use the following annotation on the class to ignore unknown properties.

@JsonIgnoreProperties(ignoreUnknown=true) public class User

11. Serializing Array of Objects to JSON

Serializing an array of objects to JSON is straightforward.

ObjectMapper mapper = new ObjectMapper(); List users = new ArrayList<>(); users.add(new User(. )); users.add(new User(. )); System.out.println(mapper.writeValueAsString(users));

The array is properly serialized as shown:

12. Deserialize Array of Objects from JSON

Several methods are available to deserialize a JSON array to a collection of Java objects. Use whatever method suits you depending on your requirements.

Deserializing a JSON array to a Java array of objects of a particular class is as simple as:

User[] users = mapper.readValue(new File(jsonFile), User[].class); System.out.println(mapper.writeValueAsString(users));

Using a JavaType is useful when constructing collections or parametric types.

JavaType listType = mapper .getTypeFactory() .constructCollectionType(List.class, User.class); List users = mapper.readValue(new File(jsonFile), listType); System.out.println(mapper.writeValueAsString(users));

A third method is to create and use a TypeReference.

TypeReference ref = new TypeReference>()<>; List users = mapper.readValue(new File(jsonFile), ref); System.out.println(mapper.writeValueAsString(users));

Summary

This article showed you how to convert Java objects to JSON and back. We also covered a few common use cases.

Источник

Оцените статью