简体   繁体   中英

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. How can I do? For HTTP requests I use 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:

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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