Java 如何在android中进行Json解析
这是网址Java 如何在android中进行Json解析,java,android,Java,Android,这是网址 http://localhost:8080/RESTfulProject/REST/WebService/GetFeeds 这种数据格式我想在Listview中解析并打印它的标题,但我无法解析它,请检查问题出在哪里。这是我的密码: [{"id":1,"title":"Tom B","description":"4006","url":"www.Norway.com"}, {"id":2,"title":"Tom c","description":"4007","url":"www.N
http://localhost:8080/RESTfulProject/REST/WebService/GetFeeds
这种数据格式我想在Listview中解析并打印它的标题,但我无法解析它,请检查问题出在哪里。这是我的密码:
[{"id":1,"title":"Tom B","description":"4006","url":"www.Norway.com"},
{"id":2,"title":"Tom c","description":"4007","url":"www.NorwayC.com"},
{"id":3,"title":"Tom D","description":"4008","url":"www.NorwayD.com"},
{"id":4,"title":"TomE","description":"www.google.com","url":"url"}]
当我运行这段代码时,它会在Jsonparser类中抛出NullPointException,请告诉我如何做,这样我就可以知道我不知道哪里出错了
package com.example.andjsonparin;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public String 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 JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return json;
}
}
还可以使用或避免在主UI线程上执行网络操作JSONArray数组=新的JSONArray(jsonString\u从\u服务器返回);
JSONArray jsonarr = new JSONArray(json);
int len=array.length();
对于(int i=0;i
当您在响应中获得JSONArray时,您必须使用JSONArray
而不是JSONObject
尝试如下:
JSONArray array=new JSONArray(jsonString_Returned_From_Server);
int len = array.length();
for(int i = 0; i < len; ++i) {
JSONObject obj = array.getJSONObject(i);
String id = obj.getString("id");
String title = obj.getString("title");
etc...
}
JSONArray json = jParser.getJSONFromUrl(url);
Log.e("JSON Parser", "Error parsing data " + json);
//Parse the values as below.
for(int i = 0; i < json.length(); ++i) {
JSONObject mobj = json.getJSONObject(i);
String id = mobj.getString("id");
String title = mobj.getString("title");
String url-mobj.getString("url");
}
这是您活动的更新代码
public static String getJSONFromUrl(String p_url) {
String m_response = null;
HttpClient client = new DefaultHttpClient();
HttpPost httpget = new HttpPost(PeakAboo.BaseUrl + p_url);
HttpResponse response;
try {
response = client.execute(httpget);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
InputStream in = response.getEntity().getContent();
StringBuilder sb = new StringBuilder();
String line = "";
BufferedReader bf = new BufferedReader(
new InputStreamReader(in));
while ((line = bf.readLine()) != null) {
sb.append(line);
}
m_response = sb.toString();
System.err.println("JSON Response--->" + m_response);
}
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return m_response;
}
@覆盖
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JSONParser jParser=新的JSONParser();
//JSONObject json=jParser.getJSONFromUrl(url);
//Log.e(“JSON解析器”,“错误解析数据”+JSON);
user=jParser.getJSONFromUrl(url);
Log.e(“JSON解析器”,“错误解析数据”+用户);
//按如下方式解析这些值。
对于(int i=0;i
如下更改您的方法
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JSONParser jParser = new JSONParser();
// JSONObject json = jParser.getJSONFromUrl(url);
// Log.e("JSON Parser", "Error parsing data " + json);
user = jParser.getJSONFromUrl(url);
Log.e("JSON Parser", "Error parsing data " + user);
//Parse the values as below.
for(int i = 0; i < user.length(); ++i) {
JSONObject mobj = user.getJSONObject(i);
String id = mobj.getString("id");
String title = mobj.getString("title");
String url=mobj.getString("url");
}
Toast.makeText(getApplicationContext(), json.toString(), Toast.LENGTH_LONG).show();
}
}
public String 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();
return json;
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
return null;
}
}
并替换main活动
,如下所示
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JSONParser jParser = new JSONParser();
// JSONObject json = jParser.getJSONFromUrl(url);
// Log.e("JSON Parser", "Error parsing data " + json);
user = jParser.getJSONFromUrl(url);
Log.e("JSON Parser", "Error parsing data " + user);
//Parse the values as below.
for(int i = 0; i < user.length(); ++i) {
JSONObject mobj = user.getJSONObject(i);
String id = mobj.getString("id");
String title = mobj.getString("title");
String url=mobj.getString("url");
}
Toast.makeText(getApplicationContext(), json.toString(), Toast.LENGTH_LONG).show();
}
}
public String 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();
return json;
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
return null;
}
}
@覆盖
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
新建GetResponseData().execute();
}
类GetResponseData扩展了AsyncTask{
私人对话;
私人ArrayList标题列表;
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
dialog=ProgressDialog.show(MainActivity.this,“,”加载“,
假);
}
@凌驾
受保护的布尔doInBackground(字符串…参数){
试一试{
JSONParser jParser=新的JSONParser();
titleList=新的ArrayList();
字符串json_response=jParser.getJSONFromUrl(url);
if(json_响应!=null){
JSONArray JSONArray=新JSONArray(json_响应);
for(int i=0;i
//以下是如何从android代码请求API的代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new GetResponseData().execute();
}
class GetResponseData extends AsyncTask<String, String, Boolean> {
private ProgressDialog dialog;
private ArrayList<String> titleList;
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog = ProgressDialog.show(MainActivity.this, "", "Loading",
false);
}
@Override
protected Boolean doInBackground(String... params) {
try {
JSONParser jParser = new JSONParser();
titleList = new ArrayList<String>();
String json_response = jParser.getJSONFromUrl(url);
if (json_response!=null) {
JSONArray jsonArray = new JSONArray(json_response);
for (int i = 0; i < jsonArray.length(); i++) {
titleList
.add(jsonArray.getJSONObject(i).getString("title"));
}
return true;
}
else
return false;
} catch (Exception exception) {
exception.printStackTrace();
return false;
}
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if (dialog != null)
dialog.dismiss();
if(result)
{
//do your stuff with titleList
}
}
}
//现在正在访问类
JsonObject response = WebAPIRequest.makeJsonObjHttpRequest(URLS.USER_REGISTRATION, "POST", params);
公共静态JSONObject MakeJSONObject HttpRequest(字符串url、字符串方法、,
列表参数){
InputStream=null;
JSONObject jObj=null;
字符串json=“”;
试一试{
如果(方法==“POST”){
DefaultHttpClient httpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(url);
setEntity(新的UrlEncodedFormEntity(参数));
HttpResponse HttpResponse=httpClient.execute(httpPost);
HttpEntity HttpEntity=httpResponse.getEntity();
is=httpEntity.getContent();
}else if(方法==“GET”){
DefaultHttpClient httpClient=新的DefaultHttpClient();
String paramString=URLEncodedUtils.format(params,“utf-8”);
url+=“”+参数字符串;
HttpGet HttpGet=新的HttpGet(url);
HttpResponse HttpResponse=httpClient.execute(httpGet);
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);
}捕获(JSONException e){
Log.e(“JSON解析器”,“错误解析数据”+e.toString());
}
//返回JSON字符串
返回jObj;
}
请参阅我最近的一篇文章,该异常的堆栈跟踪会准确地告诉您引发该异常的位置。读一下。如果您不能理解,请发布它。HttpEntity HttpEntity=httpResponse.getEntity();is=httpEntity.getContent();这样我就不会得到json=sb.toString()@user2794306请检查我已更新了您的代码并进行了相应的尝试。缓冲区错误仍然是相同的错误缓冲区错误
public static JSONObject makeJsonObjHttpRequest(String url, String method,
List<NameValuePair> params) {
InputStream is = null;
JSONObject jObj = null;
String json = "";
try {
if (method == "POST") {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} else if (method == "GET") {
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
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 JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}