[英]JSONObject with List to String to JsonNode
I convert JSONObject in string for parse it in JsonNode with jackson but i have a List in my JSONObject and when i parse it with a ObjectMapper i get this :我将字符串中的 JSONObject 转换为使用 jackson 在 JsonNode 中解析它,但是我的 JSONObject 中有一个 List,当我使用 ObjectMapper 解析它时,我得到了这个:
["{Property1 : value1, Property2 : value2}"]
And i can't call myJsonNodeObject.get(i).get("Property1")
this is my problem.而且我不能调用myJsonNodeObject.get(i).get("Property1")
这是我的问题。
I have tried to cast my List in JSONArray in my JSONObject but don't work.我试图在我的 JSONObject 中将我的 List 转换为 JSONArray 但不起作用。
resultAsJSONObject = new JSONObject();
resultAsJSONObject.put("Label", getMetricStatisticsResult.getLabel());
resultAsJSONObject.put("Datapoints", getMetricStatisticsResult.getDatapoints());
resultAsJSONObject.put("fromDate", fromDate.getTimeInMillis());
resultAsJSONObject.put("toDate", toDate.getTimeInMillis());
resultAsJSONObject.put("error", "");
resultAsString = resultAsJSONObject.toString();
mapper.readValue(resultAsString, MetricsData.class);
Assuming that you have a JSON string which you just want to change.假设您有一个只想更改的 JSON 字符串。 Then you can use Jackson to parse it as a ObjecNode
and then modify it.然后就可以用Jackson解析为一个ObjecNode
,然后修改。 Here is an example:下面是一个例子:
public class JacksonModifyJson {
static final String JSON = "{\"name\":\"Bob\", \"age\":13}";
public static void main(String[] args) throws IOException {
final ObjectMapper mapper = new ObjectMapper();
final ObjectNode jsonNode = mapper.readValue(JSON, ObjectNode.class);
jsonNode.put("url", "example.com");
System.out.println(mapper.writeValueAsString(jsonNode));
}
}
Output:输出:
{"name":"Bob","age":13,"url":"example.com"}
THis method is really easy and works too这个方法真的很简单,也很管用
try {尝试 {
JSONObject jsonObject = new JSONObject(THESTRINGHERE);
String[] names = JSONObject.getNames(jsonObject);
JSONArray jsonArray = jsonObject.toJSONArray(new JSONArray(names));
ArrayList<String> listdata = new ArrayList<String>();
JSONArray jArray = (JSONArray)jsonArray;
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
listdata.add(jArray.get(i).toString());
}
}
// System.out.println(listdata);
} catch (Exception e) {
System.out.println(e.getMessage());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.