Parsing single json entry to multiple objects with Gson

前端 未结 1 367

I have a json response that looks like this:

{
    \"id\":\"001\",
    \"name\":\"Name\",
    \"param_distance\":\"10\",
    \"param_sampling\":\"2\"
}


        
相关标签:
1条回答
  • 2021-01-19 09:44

    The way to make Gson understand it is to write a custom deserializer by creating a TypeAdapter for your Test class. You can find information in Gson's User Guide. It is not exactly a manual parsing, but it is not that different, since you have to tell Gson how to deal with each JSON value...

    It should be something like this:

    private class TestDeserializer implements JsonDeserializer<Test> {
      public Test deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
          throws JsonParseException {
    
        JsonObject obj = json.getAsJsonObject();
    
        int id = obj.get("id").getAsInt();
        String name = obj.get("name").getAsString();
    
        double distance = obj.get("param_distance").getAsDouble();
        int sampling = obj.get("param_sampling").getAsInt();
    
        //assuming you have suitable constructors...
        Test test = new Test(id, name, new Parameters(distance, sampling));
    
        return test;
      }
    }
    

    Then you have to register the TypeAdapter with:

    GsonBuilder gson = new GsonBuilder();
    gson.registerTypeAdapter(Test.class, new TestDeserializer());
    

    And finally you just have to parse your JSON as usual, with:

    gson.fromJson(yourJsonString, Test.class);
    

    Gson will automatically use your custom deserializer to parse your JSON into your Test class.

    0 讨论(0)
提交回复
热议问题