【问题标题】:In GSON, is there a way to deserialize a field in an inner class into the parent class?在 GSON 中,有没有办法将内部类中的字段反序列化为父类?
【发布时间】:2015-10-26 23:49:37
【问题描述】:

使用 GSON,如果我有一些看起来像这样的 JSON:

{
    "foo" : "asdf",
    "bar" : "jkl",
     "city": {
        "name": "Los Angeles",
        "country": "US"
    }
}

有没有办法通过使用 SerializedName 注释将其反序列化为一个看起来像这样的类?

public class SomeDto {
  String foo;
  String bar;
  String city;
  String country;
}

不必创建内部类并编写特殊的反序列化器?

也许是这样的?

@SerializedName("city.name")
private String city;

【问题讨论】:

    标签: java json serialization gson


    【解决方案1】:

    如果你需要一个单独的类,你可以将“城市”声明为地图 -

    Example.java

    import java.util.Map;
    
    public class Example {
        String foo;
        String bar;
        Map<String, String> city;
        public String getFoo() {
            return foo;
        }
        public void setFoo(String foo) {
            this.foo = foo;
        }
        public String getBar() {
            return bar;
        }
        public void setBar(String bar) {
            this.bar = bar;
        }
        public Map<String, String> getCity() {
            return city;
        }
        public void setCity(Map<String, String> city) {
            this.city = city;
        }
        @Override
        public String toString() {
            return "Example [foo=" + foo + ", bar=" + bar + ", city=" + city + "]";
        }
    }
    

    Main.java

    import com.example.Example;
    import com.google.gson.Gson;
    import com.google.gson.GsonBuilder;
    
    public class Main {
        private static Gson gson;
    
        static {
            gson = new GsonBuilder().create();
        }
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            String s = "{\"foo\":\"asdf\",\"bar\":\"jkl\",\"city\":{\"name\":\"Los Angeles\",\"country\":\"US\"}}";
            Example info = gson.fromJson(s, Example.class);
            System.out.println(info);
       }
    }
    

    结果

    Example [foo=asdf, bar=jkl, city={name=Los Angeles, country=US}]
    

    【讨论】:

      【解决方案2】:

      据我所知,没有。但是,您可以将序列化细节隐藏在一个方便的界面后面。

      例如:

      public class SomeDto {
        private String foo;
        private String bar;
        private City city;
      
        public String getFoo() {...};
        public String getBar() {...};
        public String getCity() {return city.getName();};
        public String getCountry() {return city.getCountry();};
      }
      

      【讨论】:

        猜你喜欢
        • 2011-01-13
        • 2020-07-26
        • 1970-01-01
        • 2012-07-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-21
        相关资源
        最近更新 更多