我有我原来的
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的含义值不在String双引号中,因为它是一个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();
Map<String, Object> jsonIn = gson.fromJson(data, type);
Map<String, Object> jsonOut = new HashMap<String, Object>();
Set<String> keys = jsonIn.keySet();
for (String key : keys) {
Object value = jsonIn.get(key);
if (value instanceof Map) {
Map<?, ?> mapValue = (Map<?, ?>) value;
for (Map.Entry<?, ?> entry : mapValue.entrySet()) {
jsonOut.put(key, entry.getValue());
}
} else {
jsonOut.put(key, value);
}
}
// System.out.println(jsonOut);
String json = gson.toJson(jsonOut);
System.out.println(json);
}
}
上面的代码工作正常.只有不起作用的是 – 当我尝试将jsonOut映射序列化为JSON时,某些键值无法正确显示.例如country_id和timestamp这两个键值是错误的.
所以现在我的json打印得像这样 – 你可以看到,country_id的值是3.0而不应该是3.类似的时间戳值是1.417823759555E12而应该是1417823759555
{
"u": "1235",
"p": "2047935",
"client_id": "5",
"origin":null,
"item_condition":null,
"country_id": 3.0, // this is different value
"timestamp": 1.417823759555E12, // and this is different value
"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
}
我怎么能这样做,我做错了什么?
最佳答案 默认情况下,Gson使用Double来映射任何JSON编号.既然你没有明确说明Java映射(即你已经使用过Object)
Type type = new TypeToken<Map<String, Object>>() {}.getType();
Gson将使用其默认值.
除非你指定了确切的类型,因为你的JSON似乎是动态的,因此你需要自己进行转换,然后再将它添加到最终的序列化集合中.