【发布时间】:2015-03-01 18:33:48
【问题描述】:
我需要用另一个用户 ID 模糊原始 json 字符串中存在的用户 ID。之后,我将构造一个新的 json 字符串,所有内容都相同,但唯一的区别是用户 ID 不同。
举个例子,如果我原来的json字符串是这样的——
{
"user_id":{"long":1234},
"client_id":{"int":0},
"affinity":[
{
"try":{"long":55793},
"scoring":{"float":0.19}
},
{
"try":{"long":1763},
"scoring":{"float":0.0114}
}
]
}
然后我的新 json 字符串将是 - 唯一的区别是我有一个新的用户 ID,除此之外一切都是一样的。
{
"user_id":{"long":98765},
"client_id":{"int":0},
"affinity": [
{
"try":{"long":55793},
"scoring":{"float":0.19}
},
{
"try":{"long":1763},
"scoring":{"float":0.0114}
}
]
}
我唯一的问题是,我不会只有上述格式的 json 字符串,所以我不能使用 POJO 序列化我的 json 字符串,因为我的 json 字符串会有不同的格式,但 user_id 字段将始终是这样在我所有的 json 字符串中,它也将是 long。其他字段可能会有所不同,具体取决于我拥有的 json 字符串。
我正在使用Gson 来执行此操作。我有下面的方法,但不知道如何构造一个带有newUserId 的新json,一切都应该一样?
private static String creatNewJson(String originalJsonResponse, long newUserId) {
JsonElement jelement = new JsonParser().parse(originalJsonResponse);
JsonObject jobject = jelement.getAsJsonObject();
jobject = jobject.getAsJsonObject("user_id");
// not sure what I should do here to construct a new json with newUserId
}
或者Gson 不是正确的做法?我应该为此使用正则表达式吗?
【问题讨论】:
-
你可以试试这个
jsobject.remove("long"); jsobject.addProperty("long",newValue) -
那我该如何用这个 jObject 构造完整的 json 字符串呢?
-
使用
GSON.toJson(jsonObject);google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/…很容易做到这一点 -
@viditbhatia aahh。有点困惑,我如何确保
jsonObject包含所有字段中的所有内容,包括其中的 newUserId 字段。 -
因此,由于我们没有对任何其他字段进行任何更改,它将与原始字段完全相同。但如果您仍想检查,您可以使用
jsonobject上的has(memberName)函数来完成。并检查其值。在 jsonObject 上使用getproperty(membername)函数。 google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/…
标签: java regex json string gson