简体   繁体   中英

json data fetching android

How do I fetch this data using json. I have tried this but not working. Im very much confused about how to fetch the below data. Any help appreciated

    {
    "sftid": [
        "sfta"
    ],
    "todate": 205618.268,
    "today": 5307.174,
    "sfta": 5093.717,
    "sftb": 213.457,
    "sftc": 0,
    "cropday": 21,
    "crushingday": 21,
    "vtractor": 4535.075,
    "vtruck": 532.687,
    "vbcart": 239.412,
    "yestitons": 6374,
    "ytractor": 248,
    "ytruck": 90,
    "ybcart": 40,
    "ycart": 48,
    "hr1": 515.043,
    "hr2": 625.651,
    "hr3": 706.789,
    "hr4": 626.796,
    "hr5": 630.639,
    "hr6": 608.053,
    "hr7": 604.559,
    "hr8": 776.187
}


 JSONObject jobject = new JSONObject(response);
JSONObject jsonObj = jobject.getJSONObject("todate");

You can do something like this

 JSONObject jobject = new JSONObject(response);

then

double todate = jobject.getDouble("todate");
and so on as per the data type 

or simply you can use http://www.jsonschema2pojo.org/ which will help you to convert your json data to a model class which you can use to fetch the data easily.
For this you need to use Gson library.
So suppose you created class with above link as "Myresponse" the you can use it as

Gson gson = new Gson();
Myresponse data = gson.fromJson("<your json resopnse>",Myresponse.class);

I have added screenshot for the settings you need to do on jsonschema2pojo website 在此处输入图片说明

You could try:

JSONObject jobject = new JSONObject(response.toString());
JSONObject jsonObj = jobject.getJSONObject("todate");

As you see your response contains one JSONObject which contains many elements, First element is an JSONArray rest can be taken as a double/String. It goes as follows :

JSONObject json = new JSONObject(response);
JSONArray sftid_array = json.getJSONArray("sftid");

ArrayList<String> sftid = new ArrayList();
for(int i = 0; i < sftid_array; i++) {
   sfid.put(sftid_array.getString(i));
}
double todate = json.getDouble("todate");
double today = json.getDouble("today");
double sfta = json.getDouble("sfta");
double sftb = json.getDouble("sftb");
.
.
.
and so on

You can also use Array to store data of JSONArray. Don't forget to put it in try catch as it may throw JSONException.

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