簡體   English   中英

使用json格式android解析Java中的Json麻煩

[英]Parsing Json in Java trouble with json format android

如何從我的 .json 文件中獲取以下格式的信息?:

[{"name":"My name","country":"Country name"}]

我得到以下內容:

json文件:

{"name":"My name","country":"Country name"}

Java文件:

@Override
        protected JSONObject doInBackground(String... args) {

            JsonParser jParser = new JsonParser();
            JSONObject json;
            json = jParser.getJSONFromUrl("http://example.com/myfile.json");

            System.out.println("JSON: " + json);

            if(json != null) {

                try {

                    name = json.getString("name");
                    country = json.getString("country");

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

            }

            return null;
        }

您沒有在響應中獲得JSONObject ,而是獲得了包含一個對象的JSONArray 因此這些行是錯誤的

JSONObject json;
json = jParser.getJSONFromUrl("http://example.com/myfile.json");

你應該用

JSONArray json;

然后你得到你的第 0 個對象

JSONObject wholeObject = json.getJSONObject(0);

並從中獲取字符串

name = wholeObject.getString("name");
country = wholeObject.getString("country");

你能試試這個嗎:

 protected JSONObject doInBackground(String... args) {

        JsonParser jParser = new JsonParser();
        JSONObject json;
        json = jParser.getJSONFromUrl("http://example.com/myfile.json");

        System.out.println("JSON: " + json);

        if(json != null) {

            try {
                JSONArray jsonArray = new JSONArray(json.toString());
                JSONObject newJSON = jsonArray.get(0); //first index
                name = newJSON.getString("name");
                country = newJSON.getString("country");

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

        }

        return null;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM