通过转换gson将某些特定的表导出为文件

时间:2019-04-16 20:47:21

标签: java json serialization gson android-room

我正在尝试将我的两个房间表导出到phono的目录中。我发现的方法是使用Gson转换两个表并将其保存到本地目录中。但是问题是我不知道如何将2个转换后的JSON-s合并为一个。

我的代码:

   //for first class
    Gson gson = new Gson();
    ArrayList<String> objStrings1 = new ArrayList<String>();
    for(Clas1 data: datas_1){
        objStrings.add(gson.toJson(data));
    }
    saveLocal(objStrings1)

    //for second class
    Gson gson = new Gson();
    ArrayList<String> objStrings2 = new ArrayList<String>();
    for(Clas2 data: datas_2){
        objStrings.add(gson.toJson(data));
    }
    saveLocal(objStrings2)

1 个答案:

答案 0 :(得分:0)

You can create one root Pojo and bind these two list in one class. Also, it will be faster than generating JSON for each instance and concatenate it later. See below example which shows the idea:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.commons.lang3.RandomStringUtils;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

public class GsonApp {

    public static void main(String[] args) {
        List<Class1> class1s = Arrays.asList(new Class1(), new Class1(), new Class1());
        List<Class2> class2s = Arrays.asList(new Class2(), new Class2(), new Class2());

        Pojo root = new Pojo();
        root.setClass1s(class1s);
        root.setClass2s(class2s);

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

        String json = gson.toJson(root);
        System.out.println(json);

        Pojo deserialised = gson.fromJson(json, Pojo.class);
        System.out.println(deserialised);
    }
}

class Pojo {

    private List<Class1> class1s;
    private List<Class2> class2s;

    // getters, setters, toString
}

class Class1 {

    private int id = ThreadLocalRandom.current().nextInt(100);

    // getters, setters, toString
}

class Class2 {

    private int age = ThreadLocalRandom.current().nextInt(70);
    private String name = RandomStringUtils.randomAlphanumeric(5);

    // getters, setters, toString
}

Above code prints:

{
  "class1s": [
    {
      "id": 2
    },
    {
      "id": 1
    },
    {
      "id": 3
    }
  ],
  "class2s": [
    {
      "age": 12,
      "name": "qXcaT"
    },
    {
      "age": 33,
      "name": "3wXv4"
    },
    {
      "age": 18,
      "name": "55XZ6"
    }
  ]
}

Pojos:

Pojo{class1s=[Class1{id=2}, Class1{id=1}, Class1{id=3}], class2s=[Class2{age=12, name='qXcaT'}, Class2{age=33, name='3wXv4'}, Class2{age=18, name='55XZ6'}]}