0

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

3 Answers 3

2

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 enter image description here

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

You could try:

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

2 Comments

JSONObject jobject = new JSONObject(response.toString()); JSONObject jsonObj = jobject.getJSONObject("todate"); date = jsonObj.getString("todate"); txt_date.setText(date); This isnt working
@AparnaMutnalkar sorry, I made a mistake, plz see my edited.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.