ocwirk
ocwirk

Reputation: 1089

Gson to parse JSON file where root element is not constant

I am trying to parse a json file which looks like this -

 {
  "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"
    }
  ]
 }

I am trying to use Gson to parse it and created a class to mimic it -

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;
}

I want the value of root element that is "gmps-camino" to be inserted in builder and the rest of JSON in vehiclesWithoutBuilder list. So far my attempts to parse this file are in vain as Gson thinks there is no class called gmps-camino and gives me null for both string and the list. What would be the right way to do it ?

here's the code that I am trying to parse this -

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

Upvotes: 1

Views: 2041

Answers (3)

J.R
J.R

Reputation: 2163

If you don't want to change the structure of your class try this

Change your VehicleJson as

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

And change the dynamic root key value to "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;
    }

And parse with GSON

Gson gson = new Gson();

        JsonObject jsonObject = modifyJson(json);

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

And manually map the String value of Json array to builder variable

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

Upvotes: 1

Neeraj Jain
Neeraj Jain

Reputation: 7730

Your Bean should be structured differently, It should be like this:

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);

Upvotes: 1

Prosen
Prosen

Reputation: 72

For your reference, if required you can use JSONParser and JSONArray to your code. Try the following piece of code and modify the name according to your need:

 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);
          }
      }

You need to change the names accordingly.

For reference, see "Example" on the json-simple decoding example page.

Alternatively, you can check the following GSON usage:

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

Upvotes: 1

Related Questions