来自Url的Json Parsing在Android中,不起作用

时间:2015-12-11 13:01:20

标签: android json parsing

我正在解析来自URL的数据,其得到以下提到的错误。

原始数据显示从Server.Not能够使用Json解析分割数据

请帮我解决这个错误

编辑:1

来自网址的Json回复

[
    {
        "ID": 4,
        "Name": "Vinoth",
        "Contact": "1111111111",
        "Msg": "1"
    },
    {
        "ID": 5,
        "Name": "Mani",
        "Contact": "22222222",
        "Msg": "1"
    },
    {
        "ID": 6,
        "Name": "Manoj",
        "Contact": "33333333333",
        "Msg": "1"
    }
]

错误:

org.json.JSONException: Value [{"ID":1,"Name":"Lalita","Contact":"9997162499","Msg":"1"},{"ID":2,"Name":"kumar","Contact":"123456789","Msg":"1"}] of type java.lang.String cannot be converted to JSONArray
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at org.json.JSON.typeMismatch(JSON.java:111)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at org.json.JSONArray.<init>(JSONArray.java:96)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at org.json.JSONArray.<init>(JSONArray.java:108)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at com.knowledgeflex.restapidemo.MainActivity$LoadService.onPostExecute(MainActivity.java:135)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at com.knowledgeflex.restapidemo.MainActivity$LoadService.onPostExecute(MainActivity.java:58)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at android.os.AsyncTask.finish(AsyncTask.java:632)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at android.os.AsyncTask.access$600(AsyncTask.java:177)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:102)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at android.os.Looper.loop(Looper.java:136)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5584)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at java.lang.reflect.Method.invokeNative(Native Method)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at java.lang.reflect.Method.invoke(Method.java:515)
12-11 18:23:27.249 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
12-11 18:23:27.259 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
12-11 18:23:27.259 30195-30195/com.knowledgeflex.restapidemo W/System.err:     at dalvik.system.NativeStart.main(Native Method)

MainActivity.java

public class MainActivity extends Activity {

    TextView name1,email,status,face;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final Button GetServerData = (Button) findViewById(R.id.button1);


      name1 = (TextView)findViewById(R.id.sname);
       email = (TextView)findViewById(R.id.email);
         status = (TextView)findViewById(R.id.status);
       face = (TextView)findViewById(R.id.fb);

        GetServerData.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {

                // Server Request URL
                String serverURL = "http://webapp/api/values";

                // Create Object and call AsyncTask execute Method
                new LoadService().execute(serverURL);

            }
        });

    }


    // Class with extends AsyncTask class
    private class LoadService extends AsyncTask<String, Void, Void> {

        private final HttpClient Client = new DefaultHttpClient();
        private String Content;
        private String Error = null;
        private final String TAG = null;
        String name = null;
        private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);

        TextView uiUpdate = (TextView) findViewById(R.id.textView2);

        protected void onPreExecute() {
            // NOTE: You can call UI Element here.

            // UI Element
            uiUpdate.setText("");
            Dialog.setMessage("Loading service..");
            Dialog.show();
        }

        // Call after onPreExecute method
        protected Void doInBackground(String... urls) {
            try {

                // NOTE: Don't call UI Element here.

                HttpGet httpget = new HttpGet(urls[0]);
                ResponseHandler<String> responseHandler = new BasicResponseHandler();
                Content = Client.execute(httpget, responseHandler);

            } catch (ClientProtocolException e) {
                Error = e.getMessage();
                cancel(true);
            } catch (IOException e) {
                Error = e.getMessage();
                cancel(true);
            }

            return null;
        }

        protected void onPostExecute(Void unused) {
            // Close progress dialog
            Dialog.dismiss();
            Log.e(TAG, "------------------------------------- Output: " + Content);


            try {
                JSONArray jArr=new JSONArray(Content);
                for(int i=0;i<jArr.length();i++) {
                    JSONObject json=jArr.getJSONObject(i);


                    name1.setText(json.getString("Name"));
                    email.setText(json.getString("ID"));
                    status.setText(json.getString("Contact"));
                    face.setText(json.getString("Msg"));

                }

            } catch (JSONException e) {
                e.printStackTrace();
                Log.i("EXCEPTION   ","");
            }

            uiUpdate.setText("Raw Output : " + Content);
        }



    }


}

8 个答案:

答案 0 :(得分:10)

根据您的回答,JSONArray和gson库最好在json数据解析时使用,因此在类下面使用任何类型的数据

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;


public class ApiData {
    @SerializedName("data")
    @Expose
    private JsonArray Data;

    public <T> List<T> getData(Class<T> c) {
        Type type = new ListParams(c);
        return new Gson().fromJson(Data, type);
    }

    private class ListParams implements ParameterizedType {

        private Type type;

        private ListParams(Type type) {
            this.type = type;
        }

        @Override
        public Type[] getActualTypeArguments() {
            return new Type[]{type};
        }

        @Override
        public Type getRawType() {
            return ArrayList.class;
        }

        @Override
        public Type getOwnerType() {
            return null;
        }


        @Override
        public boolean equals(Object o) {
            return super.equals(o);
        }

    }
}

创建模型类,如:

public class Model{
   String ID;
   String Name;
   String Contact;
   String msg;
}

现在解析您的数据,如:

ApiData apiData = new Gson().fromJson(Content, ApiData.class);
Lis<Model> models = apiData.getData(Model.class); 

答案 1 :(得分:6)

 try {
                Object jsonObject = new JSONTokener(Content).nextValue();
                JSONArray jArr=new JSONArray(jsonObject );
                for(int i=0;i<jArr.length();i++) {
                    JSONObject json=jArr.getJSONObject(i);
                    name1.setText(json.getString("Name"));
                    email.setText(json.getString("ID"));
                    status.setText(json.getString("Contact"));
                    face.setText(json.getString("Msg"));

                }

            } catch (JSONException e) {
                e.printStackTrace();
                Log.i("EXCEPTION   ","");
            }

直接你不能将字符串应用于数组,你应该将字符串转换为jsonobject,然后你可以对数组做对象。 希望你理解

答案 2 :(得分:6)

因为我已经在你的json中添加了转义,只是暂时存储它:

请检查下面的解析代码,它对我有用:

String response = "[\r\n    {\r\n        \"ID\": 4,\r\n        \"Name\": \"Vinoth\",\r\n        \"Contact\": \"1111111111\",\r\n        \"Msg\": \"1\"\r\n    },\r\n    {\r\n        \"ID\": 5,\r\n        \"Name\": \"Mani\",\r\n        \"Contact\": \"22222222\",\r\n        \"Msg\": \"1\"\r\n    },\r\n    {\r\n        \"ID\": 6,\r\n        \"Name\": \"Manoj\",\r\n        \"Contact\": \"33333333333\",\r\n        \"Msg\": \"1\"\r\n    }\r\n]";
        try {
            JSONArray jsonArray = new JSONArray(response); // replace response with your response string
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                Log.e("ID", jsonObject.getInt("ID") + "");
                Log.e("Name", jsonObject.getString("Name"));
                Log.e("Contact", jsonObject.getString("Contact"));
                Log.e("Msg", jsonObject.getString("Msg"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

我打印的日志:

  

12-17 15:42:54.459 9064-9064 / com.example.testapplication E / ID:4 12-17   15:42:54.459 9064-9064 / com.example.testapplication E / Name:Vinoth   12-17 15:42:54.459 9064-9064 / com.example.testapplication E /联系方式:   1111111111 12-17 15:42:54.459 9064-9064 / com.example.testapplication   E / Msg:1 12-17 15:42:54.459 9064-9064 / com.example.testapplication   E / ID:5 12-17 15:42:54.459 9064-9064 / com.example.testapplication   E /名称:Mani 12-17 15:42:54.459 9064-9064 / com.example.testapplication   E /联系人:22222222 12-17 15:42:54.459   9064-9064 / com.example.testapplication E / Msg:1 12-17 15:42:54.459   9064-9064 / com.example.testapplication E / ID:6 12-17 15:42:54.459   9064-9064 / com.example.testapplication E / Name:Manoj 12-17 15:42:54.459   9064-9064 / com.example.testapplication E /联系方式:33333333333 12-17   15:42:54.459 9064-9064 / com.example.testapplication E / Msg:1

谢谢..!

答案 3 :(得分:2)

public JSONArray (String json)的文档说它会抛出

  

如果解析失败或者没有产生JSONArray,则为JSONException。

也许他无法处理你的回答,因为一个简单的在线json解析器可以:http://json.parser.online.fr/

正如之前评论中提到的用户“Jelle van Es”,我会尝试Gson来完成这项工作。 (我会根据他的评论发表评论,但我的声誉很少xD)

答案 4 :(得分:2)

您正在使用getString&#34; ID&#34;什么时候你应该使用getInt。我测试了你在问题中提供的JSON字符串。以下代码有效:

String json =
    "[{\"ID\":4,\"Name\":\"Vinoth\",\"Contact\":\"1111111111\",\"Msg\":\"1\"},{\"ID\":5,\"Name\":\"Mani\",\"Contact\":\"22222222\",\"Msg\":\"1\"},{\"ID\":6,\"Name\":\"Manoj\",\"Contact\":\"33333333333\",\"Msg\":\"1\"}]";
try {
  JSONArray jsonArray = new JSONArray(json);
  for (int i = 0, len = jsonArray.length(); i < len; i++) {
    JSONObject jsonObject = jsonArray.getJSONObject(i);
    int id = jsonObject.getInt("ID");
    String name = jsonObject.getString("Name");
    String contact = jsonObject.getString("Contact");
    String msg = jsonObject.getString("Msg");
    System.out.println("id=" + id + ", name='" + name + "\', contact='" + contact + "\', msg='" + msg);
  }
} catch (JSONException e) {
  e.printStackTrace();
}

运行上述代码的输出:

  

id = 4,name =&#39; Vinoth&#39;,contact =&#39; 1111111111&#39;,msg =&#39; 1

     

id = 5,name =&#39; Mani&#39;,contact =&#39; 22222222&#39;,msg =&#39; 1

     

id = 6,name =&#39; Manoj&#39;,contact =&#39; 33333333333&#39;,msg =&#39; 1

如果您仍然收到错误,请发布堆栈跟踪。

答案 5 :(得分:2)

点击此链接JSONArray

你不应该直接使用你在点击web服务后得到的响应。首先将它转换为链接中给出的字符串,并在解析你的id时使用getInt()

答案 6 :(得分:1)

你可以像下面那样解析你的JSON。

                    try {
                            JSONArray _jArray = new JSONArray("YOUR_RESPONSE");
                            if (_jArray.length()>0){
                                for (int i = 0 ; i < _jArray.length();i++){
                                    JSONObject _jSObject = _jArray.getJSONObject(i);
                                    int ID = _jSObject.getInt("ID");
                                    String Name = _jSObject.getString("Name");
                                    String Contact = _jSObject.getString("Contact");
                                    String Msg = _jSObject.getString("Msg");
                                    System.out.println("Id : " + ID);
                                    System.out.println("Name : " + Name);
                                    System.out.println("Contact : " + Contact);
                                    System.out.println("Msg : " + Msg);
                                }
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

答案 7 :(得分:1)

Best way and very fast parsing of JSON is GSON liabrary 

dependacy for android studio compile 'com.google.code.gson:gson:2.3.1' OR you can download jar.

Make DTO names of all strings exactly same json of resonse.


Class ClassDTO{
    String ID;
    String Name;
    String Contact;
    String Msg;

    take gettters & setters

}

Just include this lines in your code.


JSONArray array=new JSONArray(Content);
if (array.length() > 0) {
    Gson gson = new Gson();
    int i = 0;
    while (i < array.length()) {
        list.add(gson.fromJson(array.getJSONObject(i).toString(), ClassDTO.class));
        i++;
    }    
} else {
    Toast.makeText(JobCardActivity.this, "No response from server", Toast.LENGTH_LONG).show();
}