英文:
How do I serialize a Dictionary items as flat properties of the class?
问题
我有一个类
public class Car {
public String color = null;
public String brand = null;
public HashMap<String,String> attributes;
public Car() {
this.attributes = new HashMap<>();
}
public static void main( String[] args ) {
Car car = new Car();
car.color = "Red";
car.brand = "Hyundai";
car.attributes.put("key1", "value1");
car.attributes.put("key2", "value1");
Gson gson = new Gson();
String json = gson.toJson(car);
System.out.println(json);
}
}
这当前会将我的car
对象序列化为
{"color":"Red","brand":"Hyundai","attributes":{"key1":"value1","key2":"value1"}}
但我希望从Car
类中解包并将attributes
字典序列化为单独的属性,而不是字典。理想情况下,我希望我的JSON是这样的:
{"color":"Red","brand":"Hyundai","key1":"value1","key2":"value1"}
我该如何在GSON中实现相同的效果?
英文:
I have a class
public class Car {
public String color = null;
public String brand = null;
public HashMap<String,String> attributes;
public Car() {
this.attributes = new HashMap<>();
}
public static void main( String[] args ) {
Car car = new Car();
car.color = "Red";
car.brand = "Hyundai";
car.attributes.put("key1", "value1");
car.attributes.put("key2", "value1");
Gson gson = new Gson();
String json = gson.toJson(car);
System.out.println(json);
}
}
This currently serializes my car
object into
{"color":"Red","brand":"Hyundai","attributes":{"key1":"value1","key2":"value1"}}
But I would like to unpack and serialize the attributes
Dictionary from Car
class as individual properties rather dictionary.
Ideally, i would like my json to be,
{"color":"Red","brand":"Hyundai","key1":"value1","key2":"value1"}
How do I achieve the same in GSON?
答案1
得分: 0
根据这个帖子的解释,没有简单或直接的方法来实现这一点。
如果可以使用Jackson
,可以使用@JsonUnwrapped
来实现,但是它在处理映射时不起作用,如这里所解释的。
但是有一种解决方法。
@JsonIgnore
public HashMap<String,String> attributes;
@JsonAnyGetter
public HashMap<String, String> getAttributes() {
return attributes;
}
这将有助于创建所需的JSON。
(new ObjectMapper()).writeValueAsString(car)
注意。这是一种替代方法。
英文:
As explained in this Thread, there is no easy or straight forward way to achieve this.
If there is a scope of using Jackson
, it can be achieved using @JsonUnwrapped
but it doesn't work with Maps as explained here
but there is work around.
@JsonIgnore
public HashMap<String,String> attributes;
@JsonAnyGetter
public HashMap<String, String> getAttributes() {
return attributes;
}
And this will help create the required JSON.
(new ObjectMapper()).writeValueAsString(car)
Note. This is an alternate approach.
答案2
得分: 0
使用 @JsonAnyGetter
注解在你的 attributes
属性的 getter 方法上。
英文:
Use @JsonAnyGetter
on the getter of your attributes
专注分享java语言的经验与见解,让所有开发者获益!
评论