gpt4 book ai didi

java - 如何解析数组中的 JSON 字符串

转载 作者:行者123 更新时间:2023-12-01 14:35:34 24 4
gpt4 key购买 nike

我有以下格式的 json:

{    "Result": {        "question": "Barack Obama vs Mitt Romney?",        "option": [            "Barack Obama",            "Mitt Romney",            "Other"                   ],        "percentage": [            20,            40,            80                      ]               }}

and I am using following code to parse it but this giving null pointer exception at option array.

JSONParser jParser = new JSONParser();

                    JSONObject json = jParser.getJSONObjectFromUrl(url);
Log.e("json",json.toString());

Log.e("-------url-------", ""+url);


String resultStr = json.getString("Result");
Log.e("result string ",resultStr);

JSONObject jsonObject2 = new JSONObject(resultStr);


String question_string = jsonObject2.getString("question");
Log.e("question String ",question_string);


String option_str = jsonObject2.getString("option");

JSONArray optionArray = new JSONArray(option_str);
Log.d("option array", String.valueOf(optionArray.length()));

最佳答案

你需要这样获取json数组:

JSONArray optionArray = jsonObject2.getJSONArray("option");
Log.d("option array", String.valueOf(optionArray.length()));

检查http://www.androidhive.info/2012/01/android-json-parsing-tutorial/

关于java - 如何解析数组中的 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16516250/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com