Java JSONObject,列表到字符串到JsonNode
我将JSONObject转换为字符串,以便使用jackson在JsonNode中解析它,但我的JSONObject中有一个列表,当我使用ObjectMapper解析它时,我得到以下结果:Java JSONObject,列表到字符串到JsonNode,java,jackson,jsonobject,Java,Jackson,Jsonobject,我将JSONObject转换为字符串,以便使用jackson在JsonNode中解析它,但我的JSONObject中有一个列表,当我使用ObjectMapper解析它时,我得到以下结果: ["{Property1 : value1, Property2 : value2}"] 我不能调用myJsonNodeObject.get(i).get(“Property1”)这是我的问题 我试图在JSONObject中的JSONArray中强制转换我的列表,但没有成功 resultAsJSONObjec
["{Property1 : value1, Property2 : value2}"]
我不能调用myJsonNodeObject.get(i).get(“Property1”)
这是我的问题
我试图在JSONObject中的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);
假设您有一个只想更改的JSON字符串。然后可以使用Jackson将其解析为
ObjecNode
,然后对其进行修改。以下是一个例子:
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));
}
}
输出:
{"name":"Bob","age":13,"url":"example.com"}
这种方法很简单,也很有效 试一试{
JSONObject JSONObject=新的JSONObject(字符串);
String[]names=JSONObject.getNames(JSONObject);
JSONArray JSONArray=jsonObject.toJSONArray(新的JSONArray(名称));
ArrayList listdata=新的ArrayList();
JSONArray jArray=(JSONArray)JSONArray;
如果(jArray!=null){
对于(int i=0;我能不能请你分享你的MetricsData
bean以及你如何使用它?为什么?你不需要它。问题是JSONObject(getMetricsStatisticsResult.getDatapoints()返回列表)中的列表,它被转换成字符串,格式为[{Property1:value1,Property2:value2}],但它是错误的,我需要这种格式:[{“Property1”:“value1”,“Property2:“value2”}”]。我想知道,你为什么要使用JSONObject?你可以直接删除它吗?我可以这样做吗?我使用JSONObject是因为我知道这个解决方案。你想要我删除什么?所以我添加了resultAsString=resultAsString.replace(\“[”,“[”;resultAsString=resultAsString.replace(“]\”,“]));resultAsString=resultAsString.replace(“\\\\”,“\\”);
;但我认为这是个糟糕的解决方案。
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());
}