我需要从以下数据中显示每个对象(响应)的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
我假设您有3个不同的响应,其中包含公共密钥,并且您希望从中获取公共密钥的值
如果我是正确的你可以使用流。
将json响应转换为对象列表
[
"response1",
"response2",
"response3"
]
arrayList = new Gson().fromJson(<above json>, ArrayList.class)
然后,您可以使用流获取预期值
arrayList.stream.map(<arraylistType> :: <keyName>).collect(Collectors.toList());
您的API返回JSON,这是一个字符串。您需要将“parse”转换为JavaScript对象,然后您只需访问所需键的值即可。
const parsedResponse = JSON.parse(response);
console.log(parsedResponse.object_id);
以下逻辑可行。伪代码中的示例。不直接工作。
# 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.
}
解决了解析消息的基本逻辑后,您可以找到更好的方法或内置函数来帮助您。
解决方案:我已通过以下方式解决了问题。现在一切正常。
<script type="text/javascript">
document.getElementById('test').onclick = function() {
xhr = new XMLHttpRequest();
xhr.open("GET", "filename.json or api url", true);
//xhr.open("GET", "compose.json", true);
xhr.onprogress = function(e) {
var data = e.currentTarget.responseText;
console.clear();
var data = JSON.parse(JSON.stringify(data));
data = data.replace(/(\r\n|\n|\r)/gm, "#");
data = data.replace(/##response:/g, ",");
data = data.replace(/response:/g, "");
data = data.replace(/##/g, "");
data = data.replace(/\\n/g, "\\n")
.replace(/\\'/g, "\\'")
.replace(/\\"/g, '\\"')
.replace(/\\&/g, "\\&")
.replace(/\\r/g, "\\r")
.replace(/\\t/g, "\\t")
.replace(/\\b/g, "\\b")
.replace(/\\f/g, "\\f");
// remove non-printable and other non-valid JSON chars
data = "["+data.replace(/[\u0000-\u0019]+/g,"")+"]";
var data = JSON.parse(data);
console.log(data);
}
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
console.log("Complete = " + xhr.responseText);
}
}
xhr.send();
};
</script>