繁体   English   中英

如何将json数据从字符串变量转换为要显示的数据

[英]how to convert json data from string variable to data to display

我想像这样的例子从字符串变量转换json数据:

String in = "{'employees': [{'firstName':'John' , 'lastName':'Doe' },"
                + "{  'firstName' : 'Anna'  ,  'lastName' :'Smith' },"
                + "{  'firstName' : 'Peter'  ,  'lastName' : 'Jones'  }]}";
        try {
            String country = "";
            JSONArray Array = new JSONArray(in);
            for (int i = 0; i < Array.length(); i++) {
                JSONObject sys = Array.getJSONObject(i);
                country += "  " + sys.getString("firstName");
            }

            Toast.makeText(this, country, Toast.LENGTH_LONG).show();

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            Toast.makeText(this,    e.toString(), Toast.LENGTH_LONG).show();

        };

当我尝试此代码时,出现此错误:

Error parsing data org.json.JSONException: Value 0 of type java.lang.Integer cannot be   
converted to JSONObject

尝试替换此行:

JSONArray Array = new JSONArray(in);

有了这个 :

JSONObject json = new JSONObject(in);
JSONArray Array = new JSONArray(json.getJSONArray("employees"));

尝试下面的代码:-

JSONObejct j = new JSONObejct(in);
JSONArray Array = j.getJSONArray("employees");

注意:-

  • {}表示JSONObject {employe}
  • []表示JSONArray employee[]

您的String in是具有关键employees和值JSONArray的对象。

所以,你需要分析in作为JSONObject并获得JSONArray employees从该对象。

尝试这个

String in = "{'employees': [{'firstName':'John' , 'lastName':'Doe' },"
            + "{  'firstName' : 'Anna'  ,  'lastName' :'Smith' },"
            + "{  'firstName' : 'Peter'  ,  'lastName' : 'Jones'  }]}";
    try {
        String country = "";
        JSONObject jObj = new JSONObject(in);

            JSONArray jArray = jObj.getJSONArray("employees");
            for(int j=0; j <jArray.length(); j++){
                JSONObject sys = jArray.getJSONObject(j);
                 country += "  " + sys.getString("firstName");
            }



        Toast.makeText(this, country, Toast.LENGTH_LONG).show();

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();

    };

实际上,您的JSON格式错误。

使用字符串如下

String in = "{\"employees\": [{\"firstName\": \"John\",\"lastName\": \"Doe\"},{\"firstName\": \"Anna\",\"lastName\": \"Smith\"},{\"firstName\": \"Peter\",\"lastName\": \"Jones\"}]}";

try {
    String country = "";
    JSONObject jObj = new JSONObject(in);

        JSONArray jArray = jObj.getJSONArray("employees");
        for(int j=0; j <jArray.length(); j++){
            JSONObject sys = jArray.getJSONObject(j);
             country += "  " + sys.getString("firstName");
        }



    Toast.makeText(this, country, Toast.LENGTH_LONG).show();

} catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();

};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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