我有一个表示事件的对象,我想将其序列化为 json,使用 gson 或其他库(如果更容易的话)。
我想在 json 中添加以下类型的字段:
private Map<String, String> additionalProperties;
还有另一个用例:
private Map<String, Object> additionalProperties;
但是如果我将 additionalProperties 添加到 Event 对象,并以正常方式构建 Gson:
Gson gson = BUILDER.create();
String json = gson.toJson(event);
它看起来像这样:
additional_properties: {"value1":1,"value2":"abc"}
我只想以下列形式附加到事件对象:
{"value1":1,"value2":"abc"}
这是一个示例输出 - 添加的附加属性是对象“z”和对象“advertiser”:
{"organisationid":"2345612ß","projectid":"12345678",
"place":{"placeId":"2345","last_place":"123-3"},
"advertiser":{"advertiserId":"2345a","code":"a123-3"},
"user":{"isY":false,"isHere":false,"isBuyer":false},
"x":{"identifier":"SHDG-28CHD"},
"z":{"identifier":"abcSHDG-28CHD"},
"event_type":"x_depart"}
这是它目前的样子:
{"organisationid":"2345612ß","projectid":"12345678",
"place":{"placeId":"2345","last_place":"123-3"},
additionalproperty: {"advertiser":{"advertiserId":"2345a","code":"a123-3"},
"user":{"isY":false,"isHere":false,"isBuyer":false},
"x":{"identifier":"SHDG-28CHD"},
additionalproperty: {"z":{"identifier":"abcSHDG-28CHD"}},
"event_type":"x_depart"}
最佳答案
解决这个问题的最好方法是使用一个动态添加属性的框架,但如果没有这个,您可以将其他属性添加到您的事件对象(包括@JsonIgnore 以便它不是最终 json 的一部分),从附加属性创建一个新的 JSONObject,并在序列化为 json 之前将其合并到事件 JSONObject。这样,附加属性将动态添加到生成的事件输出中。
在事件类中:
@JsonIgnore
private Map<String, Object> additionalProperties;
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
public void setAdditionalProperties(Map<String, Object> additionalProperties) {
this.additionalProperties = additionalProperties;
}
合并两个 JSONObject 的函数:
public static JSONObject mergeObjects(JSONObject source, JSONObject target) throws JSONException {
for (String key: JSONObject.getNames(source)) {
Object value = source.get(key);
if (!target.has(key)) {
// new value for "key":
target.put(key, value);
} else {
// existing value for "key" - recursively deep merge:
if (value instanceof JSONObject) {
JSONObject valueJson = (JSONObject)value;
deepMerge(valueJson, target.getJSONObject(key));
} else {
target.put(key, value);
}
}
}
return target;
}
将两个对象放在一起:
String jsonAdd = mapper.writeValueAsString(additional);
String jsonEvent = mapper.writeValueAsString(event);
JSONObject jsonAddObj = new JSONObject(jsonAdd);
JSONObject JsonEventObj = new JSONObject(jsonEvent);
JSONObject finalJson = Merge.deepMerge(jsonAddObj, JsonEventObj);
关于java - Gson转json动态添加map到对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26514173/