我有这个 json 文件作为示例:
[{"Type":"car","color":"black"},{"Type":"Motorcycle","color":"white"},....]
通过使用 Gson 库,我需要将其分离为不同的类。
我使用下面的代码来读取文件:
BufferedReader bufferedReader = new BufferedReader(new FileReader("v.json"));
下面的代码将其放入对象中:
Gson gson = new Gson();
List<vehicles> vehicles = gson.fromJson(bufferedReader, new TypeToken<List<Car>>() {}.getType());
我的问题是如何检查 "type":"car"
并将其添加到对象汽车中,并将 "type":"motorcycle"
添加到对象汽车中对象摩托车
我正在使用的 gson.fromJson 代码将所有内容添加到对象 Car 中。
谢谢
最佳答案
如果你可以使用其他库来解决你的问题。引用下图
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();
}
}
}
关于java - 使用 Gson lib 将 Json 转换为 Java 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61965082/