0

我之前问过一个关于解析 json 的问题,从那时起我找到了一个应该可以正常工作但它不能正常工作的示例。我现在拥有的代码如下:

  public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        final TextView tv = (TextView)findViewById(R.id.result);

            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);

            String username = "exampleusername";
            String password = "examplepassword";
            String url = "http://www.example.com/api/core/v1/my/";
            String unp = username+":"+password;


            class MyUser {
                  public String firstName;
                  public String lastName;
            }


            try {
                HttpClient client = new DefaultHttpClient();
                HttpGet header = new HttpGet(url);
                String encoded_login = Base64.encodeToString(unp.getBytes(), Base64.NO_WRAP);
                header.setHeader(new BasicHeader("Authorization", "Basic "+encoded_login));
                HttpResponse response = client.execute(header);
                HttpEntity entity = response.getEntity();

                BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
                for (String line; (line = reader.readLine()) != null;) {
                    if (line.isEmpty()) break; // Stop when headers are completed. We're not interested in all the HTML.
                    final String newjson = line.replaceAll("throw 'allowIllegalResourceCall is false.';", "");

                    JSONObject mainObject = new JSONObject(newjson);
                    JSONObject uniObject = mainObject.getJSONObject("firstName");

               // System.out.println(newjson + newjson.contains("firstName") + "," + newjson.contains("lastName"));
               System.out.println(uniObject);
             //   System.out.println(uniURL);
                }

使用此代码,我现在收到以下错误:

W/System.err(910): org.json.JSONException: End of input at character 0 of 
W/System.err(910): at org.json.JSONTokener.syntaxError(JSONTokener.java:450)
W/System.err(910): at org.json.JSONTokener.nextValue(JSONTokener.java:97)
W/System.err(910): at org.json.JSONObject.<init>(JSONObject.java:154)
W/System.err(910): at org.json.JSONObject.<init>(JSONObject.java:171)
W/System.err(910): at basic.authentication.BasicAuthenticationActivity.onCreate(BasicAuthenticationActivity.java:84)
W/System.err(910): at android.app.Activity.performCreate(Activity.java:4465)
W/System.err(910): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
W/System.err(910): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
W/System.err(910): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
W/System.err(910): at android.app.ActivityThread.access$600(ActivityThread.java:123)
W/System.err(910): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
W/System.err(910): at android.os.Handler.dispatchMessage(Handler.java:99)
W/System.err(910): at android.os.Looper.loop(Looper.java:137)
W/System.err(910): at android.app.ActivityThread.main(ActivityThread.java:4424)
W/System.err(910): at java.lang.reflect.Method.invokeNative(Native Method)
W/System.err(910): at java.lang.reflect.Method.invoke(Method.java:511)
W/System.err(910): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
W/System.err(910): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
W/System.err(910): at dalvik.system.NativeStart.main(Native Method)

我下拉的部分json字符串如下:

{
  "enabled" : true,
  "email" : "example@gmail.com",
  "firstName" : "example firstname",
  "lastName" : "example lastname",
  "name" : "example fullname",
  "level" : {

我现在对 json 很困惑,为什么这不起作用

4

2 回答 2

1

试试这个读取功能

public static JSONObject read(String url, String unp){

    System.out.println("Connecting to service URL : "+url);
    InputStream is = null;
    String result = "";
    // http post
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        String encoded_login = Base64.encodeToString(unp.getBytes(), Base64.NO_WRAP);
        httppost.setHeader(new BasicHeader("Authorization", "Basic "+encoded_login));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

    } catch (Exception e) {
        e.printStackTrace();
    }

    // convert response to string
    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();
        result = sb.toString();

    } catch (Exception e) {
        e.printStackTrace();
    }

    JSONObject json = null;
    try {
        json = new JSONObject(result);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return json;
}

}
  • 这里我先连接到服务
  • 下载响应
  • 将其传递给 JSONObject 创建,而不是循环执行
于 2012-07-10T13:46:25.550 回答
0

您可能想尝试编写没有空格的 Json ..

例如

{"foo":"bar"} 

代替

{
    "foo":"bar"
}
于 2012-07-10T13:18:49.337 回答