我需要从以下数据中显示每个对象(响应)的object_id
。
这是我通过Api获得的答复。建议或解决方案都将受到赞赏。
response:{"object_id":"a9951ef0","datetime":"2019-03-20T04:59:23.001Z","ignition_status":"ON"}
response:{"object_id":"8b1546924063","datetime":"2019-03-20T04:59:23.001Z","ignition_status":"OFF"}
response:{"object_id":"9b9d","datetime":"2019-03-20T04:59:23.001Z","ignition_status":"ONLINE"}
预期输出:
object_id = a9951ef0
object_id = 8b1546924063
object_id = 9b9d
答案 0 :(得分:1)
我假设您有3种不同的响应,其中包含公用密钥,并且您想从中获取公用密钥的值
如果正确,则可以使用流。
将json响应转换为对象列表
[
"response1",
"response2",
"response3"
]
arrayList = new Gson().fromJson(<above json>, ArrayList.class)
然后您可以使用流获取期望值
arrayList.stream.map(<arraylistType> :: <keyName>).collect(Collectors.toList());
答案 1 :(得分:0)
您的API返回的是字符串JSON。您需要将其“ parse”放入JavaScript对象,然后可以简单地通过所需键访问该值。
const parsedResponse = JSON.parse(response);
console.log(parsedResponse.object_id);
答案 2 :(得分:0)
以下逻辑可能有效。伪代码中的示例。无法直接工作。
# real_response is your message from API.
# Convert it into array by splitting newlines. Use different separator if needed.
responses_in_array = real_response.split("\n");
# Loop through every responses.
foreach(single_response in responses_in_array) {
# Clean responses before converting them into javascript objects.
clean_response = single_response.replace("response:", "");
real_object = JSON.Parse(clean_response);
// Do what ever you want. To access object_id, just call
// real_object.object_id.
//
// If needed, before cleaning line, check if it's not empty line.
}
解决了解析消息的基本逻辑后,您可以找到帮助您的更好方法或内置函数。
答案 3 :(得分:0)
解决方案:我已经通过以下方式解决了这个问题。现在一切正常。
call