我用于解析JSON值的代码。
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 JSONObject 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, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.i("JSON Parser", json);
} 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;
}
}
Actvity类代码
private static final String TAG_UserLoginsResult = "UserLoginsResult";
private static final String TAG_BRANCH_ID = "BRANCH_ID";
private static final String TAG_USER_NAME = "USER_NAME";
private static final String TAG_User_ID = "User_ID";
private static final String TAG_msg = "msg";
// contacts JSONArray
JSONArray loginsResult = null;
String url = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/*
* try { String URL = URLEncoder.encode(url1, "utf-8"); } catch
* (UnsupportedEncodingException e1) { // TODO Auto-generated catch
* block e1.printStackTrace(); }
*/
/*
* try{ String url =
* "http://etosxmldev.ctdi.com/WS/WCF/AVAYA-MOBILE- SERVICE/Service.svc/UserLogins"
* + URLEncoder.encode("?","UTF-8") + "LoginId" +
* URLEncoder.encode("=","UTF-8") + "samalorp" +
* URLEncoder.encode("&","UTF-8") + "passWord" +
* URLEncoder.encode("=","UTF-8") + "pass"; }catch (Exception e) { //
* TODO: handle exception }
*/
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
// http://etosxmldev.ctdi.com/WS/WCF/AVAYA-MOBILE-SERVICE/Service.svc/UserLogins?LoginId=samalorp&passWord=pass
JSONObject json = jParser
.getJSONFromUrl("http://etosxmldev.ctdi.com/WS/WCF/AVAYA-MOBILE-SERVICE/Service.svc/UserLogins");
try {
// Getting Array of Contacts
loginsResult = json.getJSONArray(TAG_UserLoginsResult);
// looping through All Contacts
for (int i = 0; i < loginsResult.length(); i++) {
JSONObject c = loginsResult.getJSONObject(i);
String BRANCH_ID = c.getString(TAG_BRANCH_ID);
String USER_NAME = c.getString(TAG_USER_NAME);
String User_ID = c.getString(TAG_User_ID);
String msg = c.getString(TAG_msg);
System.out.println("===========>>>" + BRANCH_ID);
System.out.println("===========>>>" + USER_NAME);
System.out.println("===========>>>" + User_ID);
System.out.println("===========>>>" + msg);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_BRANCH_ID, BRANCH_ID);
map.put(TAG_USER_NAME, USER_NAME);
map.put(TAG_User_ID, User_ID);
map.put(TAG_msg, msg);
// adding HashList to ArrayList
contactList.add(map);
// Intent i2 = new Intent(AndroidJSONParsingActivity.this,
// otherActivity.class);
// startActivity(i2);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
根据JSONLInt,JSON值有效。
Json值
{
"UserLoginsResult": [
{
"BRANCH_ID": "R28",
"USER_NAME": "saranya",
"User_ID": "5677",
"msg": null
}
]
}
甚至用于url编码也使用了各种选项。无法在android中找到解决方案。请给出一些想法。我知道有很多问题就像这样。但是那里给出了解决方案,但没有为我工作。
09-09 09:03:37.956: I/JSON Parser(266): <HTML><HEAD><STYLE type="text/css">#content{ FONT-SIZE: 0.7em; PADDING-BOTTOM: 2em; MARGIN-LEFT: 30px}BODY{MARGIN-TOP: 0px; MARGIN-LEFT: 0px; COLOR: #000000; FONT-FAMILY: Verdana; BACKGROUND-COLOR: white}P{MARGIN-TOP: 0px; MARGIN-BOTTOM: 12px; COLOR: #000000; FONT-FAMILY: Verdana}PRE{BORDER-RIGHT: #f0f0e0 1px solid; PADDING-RIGHT: 5px; BORDER-TOP: #f0f0e0 1px solid; MARGIN-TOP: -5px; PADDING-LEFT: 5px; FONT-SIZE: 1.2em; PADDING-BOTTOM: 5px; BORDER-LEFT: #f0f0e0 1px solid; PADDING-TOP: 5px; BORDER-BOTTOM: #f0f0e0 1px solid; FONT-FAMILY: Courier New; BACKGROUND-COLOR: #e5e5cc}.heading1{MARGIN-TOP: 0px; PADDING-LEFT: 15px; FONT-WEIGHT: normal; FONT-SIZE: 26px; MARGIN-BOTTOM: 0px; PADDING-BOTTOM: 3px; MARGIN-LEFT: -30px; WIDTH: 100%; COLOR: #ffffff; PADDING-TOP: 10px; FONT-FAMILY: Tahoma; BACKGROUND-COLOR: #003366}.intro{MARGIN-LEFT: -15px}</STYLE>
09-09 09:03:37.956: I/JSON Parser(266): <TITLE>Service</TITLE></HEAD><BODY>
09-09 09:03:37.956: I/JSON Parser(266): <DIV id="content">
09-09 09:03:37.956: I/JSON Parser(266): <P class="heading1">Service</P>
09-09 09:03:37.956: I/JSON Parser(266): <BR/>
09-09 09:03:37.956: I/JSON Parser(266): <P class="intro">Method not allowed.</P>
09-09 09:03:37.956: I/JSON Parser(266): </DIV>
09-09 09:03:37.956: I/JSON Parser(266): </BODY></HTML>
09-09 09:03:37.966: E/JSON Parser(266): Error parsing data org.json.JSONException: Value <HTML><HEAD><STYLE of type java.lang.String cannot be converted to JSONObject
09-09 09:03:37.993: D/AndroidRuntime(266): Shutting down VM
09-09 09:03:37.993: W/dalvikvm(266): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
09-09 09:03:38.006: E/AndroidRuntime(266): FATAL EXCEPTION: main
09-09 09:03:38.006: E/AndroidRuntime(266): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.testapp/com.example.testapp.AndroidJSONParsingActivity}: java.lang.NullPointerException
09-09 09:03:38.006: E/AndroidRuntime(266): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
09-09 09:03:38.006: E/AndroidRuntime(266): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
09-09 09:03:38.006: E/AndroidRuntime(266): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
09-09 09:03:38.006: E/AndroidRuntime(266): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
09-09 09:03:38.006: E/AndroidRuntime(266): at android.os.Handler.dispatchMessage(Handler.java:99)
09-09 09:03:38.006: E/AndroidRuntime(266): at android.os.Looper.loop(Looper.java:123)
09-09 09:03:38.006: E/AndroidRuntime(266): at android.app.ActivityThread.main(ActivityThread.java:4627)
09-09 09:03:38.006: E/AndroidRuntime(266): at java.lang.reflect.Method.invokeNative(Native Method)
09-09 09:03:38.006: E/AndroidRuntime(266): at java.lang.reflect.Method.invoke(Method.java:521)
09-09 09:03:38.006: E/AndroidRuntime(266): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
09-09 09:03:38.006: E/AndroidRuntime(266): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
09-09 09:03:38.006: E/AndroidRuntime(266): at dalvik.system.NativeStart.main(Native Method)
09-09 09:03:38.006: E/AndroidRuntime(266): Caused by: java.lang.NullPointerException
09-09 09:03:38.006: E/AndroidRuntime(266): at com.example.testapp.AndroidJSONParsingActivity.onCreate(AndroidJSONParsingActivity.java:66)
09-09 09:03:38.006: E/AndroidRuntime(266): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
09-09 09:03:38.006: E/AndroidRuntime(266): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
09-09 09:03:38.006: E/AndroidRuntime(266): ... 11 more
答案 0 :(得分:1)
在你的pasrser中构建一个JSON格式的字符串并将其传递给JSON对象
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
遗憾的是,该字符串不是JSON格式的,它属于异常,因此整个方法返回null,并在您的活动中调用
JSONObject json = jParser
.getJSONFromUrl("http://etosxmldev.ctdi.com/WS/WCF/AVAYA-MOBILE-SERVICE/Service.svc/UserLogins");
try {
// Getting Array of Contacts
loginsResult = json.getJSONArray(TAG_UserLoginsResult);
....
}
当你的json为null时,它将落入该catch块中,
我的建议重新检查你的JSON数据,这是一个很好的JSON validator
修改强> 你应该设置标题来定义你需要json
public JSONObject getJSONFromUrl(String url){
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
之后添加
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept", "JSON");
答案 1 :(得分:0)
@Override
protected String doInBackground(String... params) {
String response="";
try{
String url="your ulr";
response = sendRequest(url);
}catch(Exception e){
e.printStackTrace();
return "";
}
return response;
}
//String Method to fetech data from server
public String sendRequest(String url) {
String result = "";
try {
HttpClient client = new DefaultHttpClient();
HttpParams httpParameters = client.getParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 5000);
HttpConnectionParams.setTcpNoDelay(httpParameters, true);
HttpGet request = new HttpGet();
request.setURI(new URI(url));
HttpResponse response = client.execute(request);
InputStream ips = response.getEntity().getContent();
BufferedReader buf = new BufferedReader(new InputStreamReader(ips,
"UTF-8"));
StringBuilder sb = new StringBuilder();
String s;
while (true) {
s = buf.readLine();
if (s == null || s.length() == 0)
break;
sb.append(s);
}
buf.close();
ips.close();
result = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
Just used this method to fetch the valued for api.just permission on Manifest.xml for internel
答案 2 :(得分:0)
您正在一次读取8个字节的响应,并为每个8个字节添加换行符。
,如
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
删除这两个问题,它应该有效。