如何替换用gson.tojson创建的String的一部分?的Android

时间:2015-11-20 16:52:07

标签: android json gson

我有这段代码:

String json = new Gson().toJson(selectedEquipment);

所以JSON是这样的:

[
{"datetime":"Nov 20, 201514:45:00",
"latitude":0.0,
"longitude":0.0,
"model":"ENG",
"name":"null",
"serialNumber":"011",
"urgency":"HIGH_URGENCY",
"version":"null"}
]

我想删除"urgency":"HIGH_URGENCY"或将"HIGH_URGENCY"替换为“1”。

我该怎么做?

2 个答案:

答案 0 :(得分:1)

从输入元素中删除紧急属性:

selectedEquipment[0].remove("urgency");

或修改其值:

selectedEquipment[0].addProperty("urgency","1");

或在输出字符串中替换“HIGH_URGENCY”:

json = json.replace("HIGH_URGENCY", "1");

我会使用第一个或第二个解决方案,因为它在转换之前处理json对象。

答案 1 :(得分:0)

当你使用该函数“toJson”时,你将获得一个String,所以你可以简单地执行此操作

// To replace with 1
String json = new Gson().toJson(selectedEquipment);
json = json.replace("\"HIGH_URGENCY\"", "1");

// To remove
String json = new Gson().toJson(selectedEquipment);
json = json.replace("\"urgency\":\"HIGH_URGENCY\",", " ");