简体   繁体   中英

how to prepare json file using gson library

I have two plain pojo objects:

Ex:

class person{
  private String name;
  private String id;
}
class address{
  private String homeaddress;
  private String officeaddress;
}

How to create JSON file with Gson library like below:

{
    "person": [{name:"test",id:1}]
    "address": { homeaddress:testtt, "officeaddress":testzzzz}    
}

How to prepare JSON file using Gson.tojson method.

The example JSON in the question is invalid.

I'll assume that JSON of the following format is targeted, instead.

{
    "person":[{"name":"test","id":1}],
    "address":{"homeaddress":"testtt","officeaddress":"testzzzz"}
}

With Gson, you'd preferably want to use a Java data structure that exactly matches the JSON. Here's such an example.

import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;

public class Foo
{
  public static void main(String[] args)
  {
    Person person = new Person("name1", 1);
    List<Person> personList = new ArrayList<Person>(1);
    personList.add(person);
    Address address = new Address("home1", "office1");
    Thing thing = new Thing(personList, address);

    Gson gson = new Gson();
    String json = gson.toJson(thing);
    System.out.println(json);
  }
}

class Thing
{
  private List<Person> person;
  private Address address;

  Thing(List<Person> person, Address address)
  {
    this.person = person;
    this.address = address;
  }
}

class Person
{
  private String name;
  private int id;

  Person(String name, int id)
  {
    this.name = name;
    this.id = id;
  }
}

class Address
{
  private String homeaddress;
  private String officeaddress;

  Address(String homeaddress, String officeaddress)
  {
    this.homeaddress = homeaddress;
    this.officeaddress = officeaddress;
  }
}

If it's not possible to have a Java class structure that matches the target JSON structure, and you're stuck with only the original classes, then you can use a JsonWriter to build the JSON one token at a time. Here's an example.

  public static void main(String[] args) throws Exception
  {
    Person person = new Person("name1", 1);
    Address address = new Address("home1", "office1");

    StringWriter out = new StringWriter();
    JsonWriter writer = new JsonWriter(out);
    writer.setIndent("    ");
    writer.beginObject();
    writer.name("person");
    writer.beginArray().beginObject();
    writer.name("name").value(person.getName());
    writer.name("id").value(person.getId());
    writer.endObject().endArray();
    writer.name("address");
    writer.beginObject();
    writer.name("homeaddress").value(address.getHomeaddress());
    writer.name("officeaddress").value(address.getOfficeaddress());
    writer.endObject();
    writer.endObject();
    writer.close();
    System.out.println(out);
  }

For the sake of completeness, I'll also point out that a simple custom serializer could be employed to solve this problem.

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;

public class Foo
{
  public static void main(String[] args) throws Exception
  {
    Person person = new Person("name1", 1);
    Address address = new Address("home1", "office1");
    SomeContainer thing = new SomeContainer(person, address);

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Person.class, new MyCustomSerializer());
    Gson gson = gsonBuilder.create();
    System.out.println(gson.toJson(thing));
  }
}

class MyCustomSerializer implements JsonSerializer<Person>
{
  @Override
  public JsonElement serialize(Person src, Type typeOfSrc, JsonSerializationContext context)
  {
    List<Person> personList = new ArrayList<Person>();
    personList.add(src);
    return new Gson().toJsonTree(src);
  }
}

class SomeContainer
{
  Person person;
  Address address;
  SomeContainer(Person p, Address a) {person = p; address = a;}
}

class Person
{
  private String name;
  private int id;
  Person(String n, int i) {name = n; id = i;}
}

class Address
{
  private String homeaddress;
  private String officeaddress;
  Address(String h, String o) {homeaddress = h; officeaddress = o;}
}

And of course, one could construct a JsonElement tree from the original Java data structure, then manipulate the JSON tree to match the desired output, and finally serialize it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM