我一直在为这个解决方案而烦恼,我有如下的JSON字符串
{"Nodes":
[
{
"Node_id": 10023
},
{
"Node_id": 10056
},
{
"Node_id":00000
}
],
"utc":136199375611
}
如何将其转换为格式
{"Nodes":
[
{
"Node_id": "10023"
},
{
"Node_id": "10056"
},
{
"Node_id":"00000"
}
],
"utc":"136199375611"
}
现在我想用双引号“整数值”对所有整数值(它们放在值中)进行编码,如何在正则表达式中使用java Patterns和matcher类甚至子字符串类进行编码。你的帮助会很有意义。
原始的JSON格式如下所示
{
"Nodes": [
{
"Node_id": "10023",
"count": 1
},
{
"Node_id": "10056",
"count": 2
},
{
"Node_id": "+00000",
"count": 1
},
{
"Node_id": "-00000",
"count": "6"
}
],
"utc": "136199375611",
"DeliveryTime": "Tue 23rd jun 2014 12:45 AM",
"Ifr": "2333"
}
答案 0 :(得分:0)
快速修复。
jsonString.replaceAll("(\\d+)","\"$1\"")
但我建议您使用正确的JSON解析器或GSON库将其解析为Java Object,然后将Integer值转换为String,最后将该Java Object转换回JSON字符串。
示例代码:
class NodesDetail{
private ArrayList<NoteId> Nodes;
private String utc;
}
class NoteId{
private String Node_id;
}
...
NodesDetail obj = new Gson().fromJson(reader, NodesDetail.class);
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(obj));
输出:
{
"Nodes": [
{
"Node_id": "10023"
},
{
"Node_id": "10056"
},
{
"Node_id": "00000"
}
],
"utc": "136199375611"
}
根据JSON字符串
编辑POJO类以匹配class NodesDetail{
private ArrayList<NoteId> Nodes;
private String utc;
private String DeliveryTime;
private String Ifr;
}
class NoteId{
private String Node_id;
private String count;
}
...
NodesDetail obj = new Gson().fromJson(reader, NodesDetail.class);
System.out.println(new GsonBuilder().setPrettyPrinting().create().toJson(obj));
输出:
{
"Nodes": [
{
"Node_id": "10023",
"count": "1"
},
{
"Node_id": "10056",
"count": "2"
},
{
"Node_id": "+00000",
"count": "1"
},
{
"Node_id": "-00000",
"count": "6"
}
],
"utc": "136199375611",
"DeliveryTime": "Tue 23rd jun 2014 12:45 AM",
"Ifr": "2333"
}