-3

Code I am using for parssing JSON Values .

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 class code

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

}

It JSON Values are valid according to JSONLInt.

Json Values are

  {
    "UserLoginsResult": [
      {
        "BRANCH_ID": "R28",
        "USER_NAME": "saranya",
        "User_ID": "5677",
        "msg": null
     }
  ]
 }

used various option even for url encoding .Not be able to find the solution.new in android please give some idea.I know there are many question on like this.tried the solution given there but not worked for me.

    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
4

3 回答 3

1

在您的解析器中,您构建一个 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 为空,所以它会落在那个 catch 块中,
我的建议是重新检查你的 JSON 数据,这是一个很好的JSON 验证器

编辑 你应该设置标题来定义你需要json

公共 JSONObject getJSONFromUrl(字符串 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");
于 2013-09-09T06:49:53.893 回答
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
于 2013-09-09T05:55:05.567 回答
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");
    }

消除这两个问题,它应该可以工作。

于 2013-09-09T06:13:47.787 回答