【发布时间】:2015-02-04 09:51:06
【问题描述】:
我有这样的原始 JSON 字符串,其中我有如下所示的键和值 -
{
"u":{
"string":"1235"
},
"p":"2047935",
"client_id":{
"string":"5"
},
"origin":null,
"item_condition":null,
"country_id":{
"int":3
},
"timestamp":{
"long":1417823759555
},
"impression_id":{
"string":"2345HH*"
},
"is_consumerid":true,
"is_pid":false
}
例如,一个键是"u",它的值是-
{
"string":"1235"
}
同样的另一个键是"country_id",它的值是-
{
"int":3
}
现在我需要做的是,我需要表示键值对,如下所示。如果任何值是字符串数据类型(如键 u 的值),则用双引号表示它的值,否则不要用双引号表示它的值。 country_id 的含义值不会在字符串双引号中,因为它是一个 int。
"u": "1235"
"p": "2047935"
"client_id": "5"
"origin":null
"item_condition":null
"country_id": 3 // I don't have double quotes here around 3 since country_id was int that's why
"timestamp": 1417823759555
"impression_id": "2345HH*"
"is_consumerid": true
"is_pid": false
然后我需要制作另一个看起来像这样的 json 字符串 -
{
"u": "1235",
"p": "2047935",
"client_id": "5",
"origin":null,
"item_condition":null,
"country_id": 3,
"timestamp": 1417823759555,
"impression_id": "2345HH*",
"is_consumerid": true,
"is_pid": false
}
所以我从下面的代码开始,但无法理解我应该进一步做什么?
String response = "original_json_string";
Type type = new TypeToken<Map<String, Object>>() {}.getType();
JsonObject jsonObject = new JsonParser().parse(response).getAsJsonObject();
for (Map.Entry<String, JsonElement> object : jsonObject.entrySet()) {
if (object.getValue() instanceof JsonObject) {
String data = object.getValue().toString();
// now not sure what should I do here?
}
}
我的新 json 在序列化后应该像这样打印出来。
{
"u": "1235",
"p": "2047935",
"client_id": "5",
"origin":null,
"item_condition":null,
"country_id": 3,
"timestamp": 1417823759555,
"impression_id": "2345HH*",
"is_consumerid": true,
"is_pid": false
}
实现这一目标的最佳方法是什么?
【问题讨论】:
-
能否请您告诉我 JSON 的原始结构是否已修复。我的意思是每次“client_id”都会有“string”或者它也可以有“long”?
-
@ShaikhMohammedShariq 是的,它已修复。简而言之,如果任何键是字符串,它们将始终是字符串。 int、long、boolean 也是如此。
标签: java json string serialization gson