Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/184.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将简单JSON解析为android 将JSON数据解析到android时出现问题 我已经描述了我面临的问题,有什么想法吗 如何克服这个问题_Android_Json_Parsing - Fatal编程技术网

将简单JSON解析为android 将JSON数据解析到android时出现问题 我已经描述了我面临的问题,有什么想法吗 如何克服这个问题

将简单JSON解析为android 将JSON数据解析到android时出现问题 我已经描述了我面临的问题,有什么想法吗 如何克服这个问题,android,json,parsing,Android,Json,Parsing,最初我使用了来自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() { } pub

最初我使用了来自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;

    }
}
    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));


    }
}
AndroidJSONParsingActivity.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;

    }
}
    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));


    }
}
我根据错误进行的分析::

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

  • 对于URL::
    http://54.218.73.244:8084/
我得到的JSON回复是::
[{“id”:1,“content”:“Hello”},{“id”:2,“content”:“World”}]

  • 对于URL::
    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);

分析数据org.json.JSONException时出错:不能将java.lang.String类型的值转换为JSONArray

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

问题实际上与代码无关。请确保从服务器获得正确的JSON响应。

/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();

        }
    }

}
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.io.UnsupportedEncodingException;
导入java.util.ArrayList;
导入java.util.HashMap;
导入org.apache.http.HttpEntity;
导入org.apache.http.HttpResponse;
导入org.apache.http.client.ClientProtocolException;
导入org.apache.http.client.HttpClient;
导入org.apache.http.client.ResponseHandler;
导入org.apache.http.client.methods.HttpGet;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.impl.client.BasicResponseHandler;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.json.JSONArray;
导入org.json.JSONException;
导入org.json.JSONObject;
导入android.app.Activity;
导入android.app.ProgressDialog;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.util.Log;
导入android.view.Menu;
导入android.view.MenuItem;
导入android.widget.ListView;
导入android.widget.Toast;
公共类MainActivity扩展了活动{
列表视图列表;
JSONObject JSONObject;
切割适配器;
JSONArray JSONArray;
静态InputStream为空;
静态JSONObject jObj=null;
静态字符串json=“”;
ArrayList ArrayList;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list=(ListView)findViewById(R.id.list);
新getData()
.execute();
}
私有类getData扩展异步任务{
private ProgressDialog=新建ProgressDialog(MainActivity.this);
受保护的void onPreExecute(){
//注意:您可以在这里调用UI元素。
setMessage(“下载源…”);
Dialog.show();
}
@凌驾
受保护的Void doInBackground(字符串…url){
//TODO自动生成的方法存根
arraylist=新的arraylist();
试一试{
DefaultHttpClient httpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(“您的Url”);
HttpResponse HttpResponse=httpClient.execute(httpPost);
HttpEntity HttpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
}捕获(不支持的编码异常e){
e、 printStackTrace();
}捕获(客户端协议例外e){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}
试一试{
BufferedReader reader=新的BufferedReader(新的InputStreamReader(is,“iso-8859-1”),8;
StringBuilder sb=新的StringBuilder();
字符串行=null;
而((line=reader.readLine())!=null){
sb.附加(第+行“n”);
}
is.close();
json=sb.toString();
}捕获(例外e){
Log.e(“,”错误转换结果“+e.toString());
}
//尝试将字符串解析为JSON对象
试一试{
jObj=新的JSONObject(json);
JSONObject jObj1=新的JSONObject(jObj.getJSONObject(“response”).toString());
jsonarray=jObj1.getJSONArray(“场馆”);
for(int i=0;ipackage 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;
    }

}
<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>
<?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>