Export some specific tables as file by converting gson

Emma Alden :

I'm trying to export two of my room tables into phono's directory. The way I figured out is that I convert two of my tables using Gson and save it into local directory. But the problems is I don't know how to combine that 2 converted JSON-s into one.

My codes:

   //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)
Michał Ziober :

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'}]}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=166757&siteId=1