简体   繁体   English

Android,在 Java 结构中解析 JSON

[英]Android, parse JSON in a Java structure

I need to transform this JSON I receive from an HTTP server into a JAVA structure that allows me to retrieve every single data, for example the first element of the freq list.我需要将我从 HTTP 服务器收到的 JSON 转换为 JAVA 结构,该结构允许我检索每个数据,例如freq列表的第一个元素。 How can I do?我能怎么做? For HTTP requests I use OkHttpClient.对于 HTTP 请求,我使用 OkHttpClient。

 [" { "cpu": { "freq": [3193.068625, 1600.0, 3900.0], "usage": [0.0, 0.0, 2.0, 1.0, 4.9, 2.0, 1.0, 1.0], "load": [0.22, 0.18, 0.16] }, "memory": { "ram": [15.54, 13.07, 15.9, 2.04, 11.24] }, "disks": { "ssd": [219.1, 13.6, 194.2, 6.6], "hdd": [0.0, 0.0, 0, 100.0] }, "temps": { "core-0": [29.0, 85.0, 105.0], "core-1": [36.0, 85.0, 105.0], "core-2": [35.0, 85.0, 105.0], "core-3": [33.0, 85.0, 105.0] } } "]

Having the response as a JSONObject, and knowing the format of response, you may use this:将响应作为 JSONObject 并知道响应的格式,您可以使用以下命令:

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

// ...
   

JSONObject opt = response.getJSONObject("opt");
JSONObject cpu = opt.getJSONObject("cpu");
JSONArray jsonArrayfreq = cpu.getJSONArray("freq");    

// Finally, charge the JSONArray into your own list and process it.
List<Double> myList = new Gson().fromJson(jsonArrayfreq.toString(), new TypeToken<List<Double>>(){}.getType());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM