首页 文章

json数据获取android

提问于
浏览
1

如何使用json获取此数据 . 我试过这个但没有用 . 我非常困惑如何获取以下数据 . 任何帮助赞赏

{
    "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 回答

  • 1

    如您所见,您的响应包含一个包含许多元素的JSONObject,第一个元素是JSONArray,其余可以作为double / String . 它如下:

    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
    

    您还可以使用Array来存储JSONArray的数据 . 不要忘记把它放在try catch中,因为它可能抛出JSONException .

  • 3

    你可以尝试:

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

    你可以做这样的事情

    JSONObject jobject = new JSONObject(response);
    

    然后

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

    或者只是你可以使用http://www.jsonschema2pojo.org/这将帮助你将你的json数据转换为一个模型类,你可以使用它来轻松获取数据 .
    为此,您需要使用Gson库 .
    因此,假设您创建了具有上述链接的类作为 "Myresponse" ,您可以将其用作

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

    我已经在jsonschema2pojo网站上添加了你需要做的设置的截图

相关问题