Gson解析根元素不是常量的JSON文件

时间:2017-11-21 05:21:20

标签: java json gson

我正在尝试解析一个看起来像这样的json文件 -

 {
  "gmps-camino": [
    {
      "id": "2903315183",
      "category": "NEW",
      "year": "2016",
      "make": "Chevrolet",
      "model": "4500 Gas",
      "trim": "2WD Reg Cab 150"",
      "type": "",
      "price": "56001.000000",
      "photo": "http://inventory-dmg.assets-cdk.com/chrome_jpgs/2016/24174x90.jpg"
    },
    {
      "id": "2774517143",
      "category": "NEW",
      "year": "2016",
      "make": "Chevrolet",
      "model": "Cruze",
      "trim": "Sedan L",
      "type": "CAR",
      "price": "17495.000000",
      "photo": "http://inventory-dmg.assets-cdk.com/RTT/Chevrolet/2016/3077853/default/ext_GAZ_deg01x90.jpg"
    }
  ]
 }

我正在尝试使用Gson解析它并创建一个类来模仿它 -

public class VehicleJson {
  String builder
  List<VehicleWithoutBuilder> vehiclesWithoutBuilder;
}

class vehicleWithoutBuilder {
  String id;
  String Category;
  String year;
  String make;
  String model;
  String trim;
  String type;
  Double price;
  String photo;
}

我希望root元素的值是&#34; gmps-camino&#34;要在vehiclesWithoutBuilder列表中插入构建器和JSON的其余部分。到目前为止,我试图解析这个文件是徒劳的,因为Gson认为没有一个名为gmps-camino的类,并且对于字符串和列表都给我null。什么是正确的方法呢?

这里是我试图解析的代码 -

BufferedReader br = new BufferedReader(new FileReader(jsonFileName));
Gson gson = new Gson();
VehicleJson vj = gson.fromJson(br, VehicleJson.class);

3 个答案:

答案 0 :(得分:1)

你的Bean应该采用不同的结构,它应该是这样的:

public class VehicleJson {
  Map<String,List<VehicleWithoutWebID>> vehicles;
}

// Now lets parse the JSON and construct the BEAN
VechicleJson vehicleJson = new Gson().fromJson("yourInput.json",VehicleJson.class);

答案 1 :(得分:1)

供您参考,如果需要,您可以使用JSONParserJSONArray代码。尝试以下代码并根据您的需要修改名称:

 JSONParser parser = new JSONParser();

   try {   

          Object objct = parser.parse(new FileReader("...")); //the location/name of your json file
          JSONObject jsonObject = (JSONObject) objct;
          JSONArray objs = (JSONArray) jsonObject.get("gmps-camino");
          for (Object obj : objs) {
               JSONObject jobj = (JSONObject) obj;
               String gmps = (String) jobj.get("gmps-camino");
               System.out.println(gmps);
          }
      }

您需要相应地更改名称。

有关参考,请参阅json-simple decoding example页面上的“示例”。

或者,您可以检查以下GSON用法:

private static final Type VEHICLE = new TypeToken<List<vehicleWithoutBuilder>>() {
}.getType();

    Gson gson = new Gson();
    JsonReader reader = new JsonReader(new FileReader(filename));
    List<vehicleWithoutBuilder> data = gson.fromJson(reader, VEHICLE ); // contains the whole list
    data.toScreen(); // prints to screen some values

答案 2 :(得分:1)

如果您不想更改班级的结构,请尝试以下

将您的VehicleJson更改为

public class VehicleJson {
  String builder;
  @SerializedName("myKey")
  List<VehicleWithoutBuilder> vehiclesWithoutBuilder;
}

将动态根密钥值更改为“myKey”

public JsonObject modifyJson(String inputJson) {
        JsonParser parser = new JsonParser();
        JsonObject jsonObject = parser.parse(inputJson).getAsJsonObject();

        //Get the random key
        String key = jsonObject.keySet().iterator().next();

        //Take a copy of the Array
        JsonElement copyArray = jsonObject.get(key);

        //Remove from JsonObject
        jsonObject.remove(key);

        String customKey = "myKey";

        jsonObject.add(customKey , copyArray);

        return jsonObject;
    }

用GSON解析

Gson gson = new Gson();

        JsonObject jsonObject = modifyJson(json);

        VehicleJson result = gson.fromJson(jsonObject, VehicleJson.class);

并手动将Json数组的String值映射到构建器变量

result.builder = jsonObject.getAsJsonArray("myKey").toString();