pojo parse gson with invalid java names

后端 未结 3 921
滥情空心
滥情空心 2021-01-04 03:51

i\'m working with the youtube json from google-api-client :

{
    \"apiVersion\": \"2.0\",
    \"data\": {
        \"updated\": \"2011-01-05T13:48:33.146Z\",         


        
相关标签:
3条回答
  • 2021-01-04 04:24

    Just say it from my personal experience, @Key may not work on serialization/de-serialization when choosing the wrong Json parser.

    (1) When you use Gson parser, like below :

    GsonBuilder gsb = new GsonBuilder();
    Gson gson = gsb.create();
    OneDriveItem oneDriveItem = gson.fromJson(jasonData1, OneDriveItem.class);
    

    @Key does not work, you should use @SerializedName to annotate the field name.

    (2) When you use JsonFactory from the package com.google.api.client.json, like below :

     JacksonFactory jsonFactory=new JacksonFactory();
    

    @Key should work.

    0 讨论(0)
  • 2021-01-04 04:25

    If you're using the @Key annotation for your mapped fields, you just need to make use of a custom value that can be passed to this annotation. So choose a legal name for your field and map it as @Key("default"):

    @Key("default")
    private String defaultUrl;
    
    0 讨论(0)
  • 2021-01-04 04:47

    I believe your answer lies in the JSON Field Naming Support:

    Gson supports some pre-defined field naming policies to convert the standard Java field names (i.e. camel cased names starting with lower case --- "sampleFieldNameInJava") to a Json field name (i.e. sample_field_name_in_java or SampleFieldNameInJava).

    See for instance the following example:

    private class SomeObject {
      @SerializedName("custom_naming") private final String someField;
      private final String someOtherField;
    
      public SomeObject(String a, String b) {
        this.someField = a;
        this.someOtherField = b;
      }
    }
    

    So you should be able to define the field mapping to the default value like this:

    @SerializedName("default")
    private final String someOtherNameThanDefault;
    
    0 讨论(0)
提交回复
热议问题