0

I have this json file as example:

[{"Type":"car","color":"black"},{"Type":"Motorcycle","color":"white"},....]

By using the Gson lib I need to separate it for differents classes.

I'm using the code below to read the file :

BufferedReader bufferedReader = new BufferedReader(new FileReader("v.json"));

And the code below to put it in a object:

    Gson gson = new Gson();
    List<vehicles> vehicles = gson.fromJson(bufferedReader, new TypeToken<List<Car>>() {}.getType());

My question is how can I check the "type":"car" and add it to an Object Car and the "type":"motorcycle" to an Object Motorcycle

The gson.fromJson code I'm using is adding all to an object Car.

Thanks

Özgür Can Karagöz
  • 1,039
  • 1
  • 13
  • 32
guidev
  • 3
  • 2
  • 1
    Does this answer your question? [Gson serialize a list of polymorphic objects](https://stackoverflow.com/questions/19588020/gson-serialize-a-list-of-polymorphic-objects) – Tefek May 23 '20 at 00:18

1 Answers1

0

If you can use other libraries to solve your problem. Refer the below one

import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import com.google.gson.Gson;

class Car {
private String color;
private String Type;
}

class MotorCycle {
private String color;
private String Type;
}

 public class Test {

public static void main(String[] args) {
    try {
        List<Car> listOfCar = new ArrayList();
        List<MotorCycle> listOfMotorCycle = new ArrayList();
        JSONParser parser = new JSONParser();
        JSONArray jsonList;
        Gson gson = new Gson();

        jsonList = (JSONArray) parser.parse(new FileReader("v.json"));

        Iterator listOfJsonObject = jsonList.iterator();
        JSONObject jsonObject;
        while (listOfJsonObject.hasNext()) {
            jsonObject = (JSONObject) listOfJsonObject.next();
            if (jsonObject.get("Type").equals("car")) {
                listOfCar.add(gson.fromJson(jsonObject.toString(), Car.class));
                continue;
            }
            listOfMotorCycle.add(gson.fromJson(jsonObject.toString(), MoterCycle.class));
        }

        // you can use your list of car and motorcycle further

    } catch (IOException | ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
}
Mr. Jain
  • 146
  • 1
  • 2
  • 15