android gson java json Latest

Gson – How to structure JSON – Mkyong.com

Gson presents easy Json () and Json () methods for converting Java objects from JSON / JSON.

Gson gson = New Gson ();

// 1. Java object within the JSON file
gson.toJson (obj, new FileWriter ("C: fileName.json"));

// 2. Java object for the JSON string
String json = gson.toJson (obj);

from John () – JSON and Java

Gson gson = New Gson ();

// 1. JSON file for Java object
Object object = gson.fromJson (new FileReader ("C: fileName.json"), Object.class);

// 2. JSON string for Java object
The string json = "& # 39; name & # 39 ;: & # 39; mkyong & # 39;";
Object object = gson.fromJson (json, Employees.class);

1. Obtain Gson

pom.xml

com.google.code.gson
gson
2.eight.5

2. Java object

For later testing

Employees.java

package deal com.mkyong;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Record;
import java.util.Map;

public class employees

personal language identify;
personal age;
personal language []; // array
personal record ; // listing
personal map ; // map

// getter and setter

3. Java Objects for JSON

3.1 At Gson we will use gson.toJson () to convert Java objects to JSON.

GsonExample1.java

package deal com.mkyong;

Import com.google.gson.Gson;
Import com.google.gson.GsonBuilder;

import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class GsonExample1

public Static void major (String [] args)

// fairly print
Gson gson = new GsonBuilder (). SetPrettyPrinting (). Create ();

Employees Employees = createStaffObject ();

// Java objects to the string
String json = gson.toJson (employees);

//System.out.println(json);

// Java objects to file
attempt (FileWriter Writer = new FileWriter ("c: testimies.json"))
gson.toJson (employees, writer);
in the hall (IOException e)
e.printStackTrace ();

personal static employees createStaffObject ()

Employees employees = new employees ();

employees.setName ("mkyong");
employees.setAge (35);
employees.setPosition (new language [] "Founder", "CTO", "Writer");
Map salary = new HashMap ()
put ("2010", the new BigDecimal (10000));
put ("2012", the brand new BigDecimal (12000));
put ("2018", the new BigDecimal (14000));
;
employees.setSalary (salary);
employees.setSkills (Arrays.asList ("java", "python", "node", "Kotlin"));

return of personnel;

Power

c: Testing Employees.Json

"name": "mkyong"
"age": 35,
"station": [
“Founder”,
“CTO”,
“Writer”
] "Skills": [
“java”,
“python”,
“node”,
“kotlin”
] "pay":
"2018": 14000,
"2012": 12,000
"2010": 10,000

4. JSON and Java Objects

4.1 At Gson, we will use gson.fromJson to convert JSON again to a Java object.

GsonExample2.java

package deal com.mkyong;

Import com.google.gson.Gson;

import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

public class GsonExample2

public Static void most important (String [] args)

Gson gson = New Gson ();

attempt (Reader Reader = new FileReader ("c: testimies.json"))

// Convert JSON file to Java object
Employees employees = gson.fromson (reader, Employees.class);

// print service
System.out.println (employees);

in the hall (IOException e)
e.printStackTrace ();

Energy

Employees identify = & # 39; mkyong & # 39 ;, age = 35, location = [Founder, CTO, Writer] expertise = [java, python, node, kotlin] salary = 2018 = 14000, 2012 = 12000, 2010 = 10000

5. Pretty Print JSON

5.1 The default JSON output is compact.

GsonExample3.java

package deal com.mkyong;

Import com.google.gson.Gson;

public class GsonExample3

public Static void primary (String [] args)

// compact printing
Gson gson = New Gson ();

The string [] lang = "Java", "Node", "Kotlin", "JavaScript";
String json = gson.toJson (lang);

System.out.println (json);

Output

[“Java”,”Node”,”Kotlin”,”JavaScript”]

5.2 Pretty Startup Printing

GsonExample4.java

package deal com.mkyong;

Import com.google.gson.Gson;
Import com.google.gson.GsonBuilder;

public class GsonExample4

public Static void important (String [] args)

// fairly print
Gson gson = new GsonBuilder (). SetPrettyPrinting (). Create ();

The string [] lang = "Java", "Node", "Kotlin", "JavaScript";
String json = gson.toJson (lang);

System.out.println (json);

Power

[
“Java”,
“Node”,
“Kotlin”,
“JavaScript”
]

6. Excluding Fields

Gson has some ways to exclude certain fields

6.1 By default, transient and static fields are omitted. We will override the default worth by closingFieldsWithModifiers

If we solely need to exclude static fields.

import java.lang.mirror.Modifier;

Gson gson = new GsonBuilder ()
.excludeFieldsWithModifiers (Modifier.STATIC)
.create();

If we would like to exclude momentary and static fields, default

import java.lang.mirror.Modifier;

Gson gson = new GsonBuilder ()
.excludeFieldsWithModifiers (Modifier.STATIC, Modifier.TRANSIENT)
.create();

This configuration takes under consideration static and transient fields.

Gson gson = new GsonBuilder ()
.excludeFieldsWithModifiers ()
.create();

6.2 Deleting fields with the @ Expose software

@Expose determines which fields are neglected of the collection and desertification for JSON. If you’d like to use @Exject, we’d like to create a Gson object like:

Gson gson = new GsonBuilder ()
.excludeFieldsWithoutExposeAnnotation ()
.create();

If .excludeFieldsWithoutExposeAnnotation () mode is enabled, all fields that don’t have @Expose can be omitted. For instance

import com.google.gson.annotations.Expose;

public class employees

@Expose (serialize = true, deserialize = true)
personal language identify;
@Expose
personal age;
@Expose (serialize = false, deserialize = true)

personal language [];
personal record ;
personal map ;

If the above Java object is converted to JSON, the result is

"name": "mkyong"
"age": 35

6.3 Remove fields by excludingStrategies, tags, sort, area identify, and so on. Gson is versatile.

Customized Tag @ExcludeField

ExcludeField.java

package deal com.mkyong;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention (RetentionPolicy.RUNTIME)
@Target (ElementType.FIELD)
public @interface ExcludeField

ExclusionStrategy determines which fields must be omitted or ignored

CustomExclusionStrategy.java

package deal com.mkyong;

import com.google.gson.ExclusionStrategy;
Deliver com.google.gson.FieldAttributes;

public class CustomExclusionStrategy implements ExclusionStrategy

personal remaining class typeToSkip;

public CustomExclusionStrategy (class typeToSkip)
this.typeToSkip = typeToSkip;

@Bypass
public boolean shouldSkipField (FieldAttributes f)

// if the sector identify & # 39; pay & # 39;
if ("salary" .equal (f.getName ()))
return true;

// if found in @ExcludeField, skip
if (f.getAnnotation (ExcludeField.class)! = null)
return true;

burns false;

@Bypass
public boolean shouldSkipClass (category Clazz)
return (Clazz == typeToSkip);

Assessment the Personnel Object again.

Employees.java

public class employees

personal language identify;
personal age;
@ExcludeField
personal language [];
personal listing ;
personal map ;

Disable ExclusionStrategy Mode.

Gson gson = new GsonBuilder ()
.setExclusionStrategies (new CustomExclusionStrategy (Listing.class)) // close all record fields.
.create();

Outcome, this instance, subject identify pay, @ ExcludeField fields, and listing sort fields are omitted.

"Name": "mkyong", "age": 35

7. Null Object Help

Null Object Fields Ignored

GsonExample5 and Java

package deal com.mkyong;

Import com.google.gson.Gson;

public class GsonExample5

public Static void most important (String [] args)

Gson gson = New Gson ();

Employees Employees = createStaffObject ();

String json = gson.toJson (employees);

System.out.println (json);

personal static employees createStaffObject ()

Employees employees = new employees ();

employees.setName ("mkyong");
employees.setAge (35);

return of personnel;

Power

"Name": "mkyong", "age": 35

Displaying Null

Gson gson = new GsonBuilder (). SerializeNulls (). Create ();

Energy

"Name": "mkyong", "age": 35, "to position": null, "skills": zero, "salary": null

eight. JSON Subject Naming Help

Default

public class employees

personal language identify;

Energy

"Name": "abc"

Customized Area Identify @SerializedName

public class employees

@SerializedName ("mkyong_name")
personal language identify;

Energy

"Mkyong_name": "abc"

9. Version Help

convey com.google.gson.annotations.Since;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Listing;
import java.util.Map;

public class employees

@Since (1.zero)
personal language identify;

@Since (2.0)
personal age;

@Since (three.zero)
personal language [];

personal listing ;
personal map ;

In this instance, the sector position (model 3) is omitted.

Gson gson = new GsonBuilder ()
.serializeNulls ()
.setVersion (2.zero) // version <= 2.zero can be included.
.create();

Power

"Name": null, "age": zero, "skills": zero, "pay": null

10. Incessantly Asked Questions

Some Widespread Questions

10.1 Converting JSON to Object Listing using TypeToken

GsonExample4.java

package deal com.mkyong;

Import com.google.gson.Gson;
import com.google.gson.mirror.TypeToken;

import java.util.Listing;

public class GsonExample4

public Static void primary (String [] args)

Gson gson = New Gson ();
String json = "[“name”:”mkyong”, “name”:”laplap”]";
Record listing = gson.fromJson (json, new TypeToken <Record > () .getType ());
record.forEach (x -> System.out.println (x));

Energy

Employees identify = & # 39; mkyong & # 39 ;, age = zero, location = zero, expertise = zero, wage = null
Employees identify = & # 39; tab & age = 0, location = zero, expertise = zero, salary = zero

10.2 Converting JSON to Map

GsonExample5 and Java

package deal com.mkyong;

Import com.google.gson.Gson;
import com.google.gson.mirror.TypeToken;

import java.util.Map;

public class GsonExample5

public Static void primary (String [] args)

Gson gson = New Gson ();

String json = "" identify ":" mkyong "," age ": 33";
Map map = gson.fromJson (json, new TypeToken <Map > () .getType ());
map.forEach ((x, y) -> System.out.println ("key:" + x + ", value:" + y));

Power

key: identify, value: mkyong
Key: Age, Value: 33.zero

References