繁体   English   中英

将简单的JSON解析为android

[英]Parsing simple JSON to android

将JSON数据解析到android时遇到问题

  • 我已经描述性地提到了我面临的问题,关于如何克服这一问题的任何想法

最初我使用url中的JSON

URL:: http://54.218.73.244:8084/

JSONParser.java

public class JSONParser {

    static InputStream is = null;
    static JSONArray jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONArray getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();           

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONArray(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

AndroidJSONParsingActivity.java

    public class AndroidJSONParsingActivity extends Activity {

        // url to make request
        private static String url = "http://54.218.73.244:8084/";
        private HashMap<Integer, String> contentsMap = new HashMap<Integer, String>();


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.on

Create(savedInstanceState);
        setContentView(R.layout.activity_main);
            // Creating JSON Parser instance
            JSONParser jParser = new JSONParser();

            // getting JSON string from URL
            JSONArray json = jParser.getJSONFromUrl(url);

            try {
                for (int i = 0; i < json.length(); i++) {
                    JSONObject c = json.getJSONObject(i);

                    // Storing each json item in variable
                    int id = c.getInt("id");
                    String name = c.getString("content");

                    contentsMap.put(id, name);
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    @Override
    protected void onResume() {
        super.onResume();

        TextView textView=(TextView) findViewById(R.id.textView1);
        textView.setText(contentsMap.get(1));

        textView=(TextView) findViewById(R.id.textView2);
        textView.setText(contentsMap.get(2));


    }
}

activity_main.xml中

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" 
    android:padding="10sp">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:padding="10sp"
        android:text="TextView1" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:padding="10sp"
        android:text="TextView2" />

</LinearLayout>

输出::

上面获得的代码的输出是

图。1


接下来,我将网址更改为

URL:: http://54.218.73.244:7003/

而且无需更改代码的其他部分

现在我得到错误屏幕

图-2-


错误日志

08-10 09:45:41.731: E/JSON Parser(448): Error parsing data org.json.JSONException: Value Cannot of type java.lang.String cannot be converted to JSONArray
08-10 09:45:41.737: D/AndroidRuntime(448): Shutting down VM
08-10 09:45:41.737: W/dalvikvm(448): threadid=1: thread exiting with uncaught exception (group=0x40015560)
08-10 09:45:41.772: E/AndroidRuntime(448): FATAL EXCEPTION: main
08-10 09:45:41.772: E/AndroidRuntime(448): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.json_web/com.example.json_web.AndroidJSONParsingActivity}: java.lang.NullPointerException
08-10 09:45:41.772: E/AndroidRuntime(448):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
08-10 09:45:41.772: E/AndroidRuntime(448):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
08-10 09:45:41.772: E/AndroidRuntime(448):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
08-10 09:45:41.772: E/AndroidRuntime(448):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)

我根据错误进行分析::

  • 解析字符串时出错,无法转换为JSONArray
  • 如何解决这个错误?

  • 网址:: http://54.218.73.244:8084/

我得到的JSON回复是:: [{"id":1,"content":"Hello"},{"id":2,"content":"World"}]

  • 网址:: http://54.218.73.244:7003/

我得到的JSON回复是:: [{"id":1,"content":"Hello"},{"id":2,"content":"World"}]

JSON的结构相同,请在浏览器中使用url进行确认


谢谢,


您位于http://54.218.73.244:7003/服务器不支持POST请求。

因此,要么使您的服务器接受POST请求,要么更改JSONParser类中的以下行。

//HttpPost httpPost = new HttpPost(url); //Remove this and replace with the below

HttpGet httpGet = new HttpGet(url);

//MainActivity.java

包com.example.jsonparsing;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {

    ListView list;
    JSONObject jsonobject;
    CutsomAdapter adapter;
    JSONArray jsonarray;
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
    ArrayList<HashMap<String, String>> arraylist;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        list = (ListView) findViewById(R.id.list);
        new getData()
                .execute();
    }

    private class getData extends AsyncTask<String, Void, Void> {
        private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);

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

            Dialog.setMessage("Downloading source..");
            Dialog.show();
        }

        @Override
        protected Void doInBackground(String... url) {
            // TODO Auto-generated method stub
                arraylist = new ArrayList<HashMap<String, String>>();

                try {

                    DefaultHttpClient httpClient = new DefaultHttpClient();
                    HttpPost httpPost = new HttpPost("Your Url");

                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    HttpEntity httpEntity = httpResponse.getEntity();
                    is = httpEntity.getContent();           

                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                try {

                    BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
                    StringBuilder sb = new StringBuilder();
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line+"n");
                    }
                    is.close();
                    json = sb.toString();



                } catch (Exception e) {
                    Log.e("", "Error converting result " + e.toString());
                }

                // try parse the string to a JSON object
                try {
                    jObj = new JSONObject(json);
                    JSONObject jObj1 = new JSONObject(jObj.getJSONObject("response").toString());
                    jsonarray = jObj1.getJSONArray("venues");

                    for (int i = 0; i < jsonarray.length(); i++) {

                        HashMap<String, String> map = new HashMap<String, String>();
                        JSONObject c = jsonarray.getJSONObject(i);
                       // JSONObject c1 = jsonarray1.getJSONObject(i);
                        // Retrive JSON Objects
                        map.put("name", c.getString("name"));
                        Log.e("Name", c.getString("name"));
                        HashMap<String, String> map1 = new HashMap<String, String>();
                        JSONObject jObj3 = new JSONObject(c.getString("location"));
                        if(jObj3.has("formattedAddress"))
                       map.put("address", jObj3.getString("formattedAddress"));

                        arraylist.add(map);
                    }
                } catch (JSONException e) {
                    Log.e("", "Error parsing data " + e.toString());
                }
                    return null;
        }

        protected void onPostExecute(Void result) {

            Log.e("Responce", arraylist.toString());
            adapter=new CutsomAdapter(MainActivity.this,arraylist);
            list.setAdapter(adapter);
            Dialog.dismiss();

        }
    }

}

//customadapter.java

package com.example.jsonparsing;

import java.util.ArrayList;
import java.util.HashMap;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class CutsomAdapter extends BaseAdapter {

    private ArrayList<HashMap<String, String>> values;
    private Context context;
    LayoutInflater inflater;

    public CutsomAdapter(Context context,
            ArrayList<HashMap<String, String>> arraylist) {
        this.context = context;
        this.values = arraylist;
    }

    @Override
    public int getCount() {
        return values.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View itemView = inflater.inflate(R.layout.row, parent, false);
        TextView textname = (TextView) itemView.findViewById(R.id.name);
        TextView textaddress = (TextView) itemView
                .findViewById(R.id.address);

        textname.setText(values.get(position).get("name"));
        textaddress.setText(values.get(position).get("address"));

        return itemView;
    }

}

//activitymain.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >
    </ListView>

</RelativeLayout>

//row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView 
        android:id="@+id/name"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:text="name"
        android:layout_marginLeft="5dp"/>
    <TextView 
        android:id="@+id/address"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:text="addess"
        android:layout_marginLeft="5dp"/>

</LinearLayout>

解析数据org.json.JSONException时出错:无法将类型java.lang.String类型的值转换为JSONArray

从错误日志中可以看到,问题是您尝试解析的JSON字符串无效。

问题实际上与代码无关,只要确保您从服务器获得正确的JSON响应即可。

暂无
暂无

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

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