2013-09-28 303 views
0

我想解析Json到字符串,以在listView上显示它。我搜索和阅读大量的文章和问题,但我不能找到解决办法解析Json到字符串

我已经试过这JSON解析器来源:Android JSON Parsing Tutorial

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, "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; 

    } 
} 

而另一个来自How to parse JSON in Android

DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams()); 
HttpPost httppost = new HttpPost("http://someJSONUrl.com/jsonWebService"); 
// Depends on your web service 
httppost.setHeader("Content-type", "application/json"); 

InputStream inputStream = null; 
String result = null; 
try { 
HttpResponse response = httpclient.execute(httppost);   
HttpEntity entity = response.getEntity(); 

inputStream = entity.getContent(); 
// json is UTF-8 by default 
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8); 
StringBuilder sb = new StringBuilder(); 

String line = null; 
while ((line = reader.readLine()) != null) 
{ 
    sb.append(line + "\n"); 
} 
result = sb.toString(); 
} catch (Exception e) { 
    // Oops 
} 
finally { 
    try{if(inputStream != null)inputStream.close();}catch(Exception squish){} 
} 

但在他们两人当我使用字符串JSON时,一切都很好,但是当我想从Web API读取Json时(例如:http://api.androidhive.info/contacts/),这个错误在我看来:

09-27 23:47:11.015: E/AndroidRuntime(28635): FATAL EXCEPTION: main 
09-27 23:47:11.015: E/AndroidRuntime(28635): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mas.forcheksulotion/com.mas.forcheksulotion.MainActivity}: java.lang.NullPointerException 
09-27 23:47:11.015: E/AndroidRuntime(28635): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1666) 
09-27 23:47:11.015: E/AndroidRuntime(28635): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1682) 
09-27 23:47:11.015: E/AndroidRuntime(28635): at android.app.ActivityThread.access$1500(ActivityThread.java:117) 
09-27 23:47:11.015: E/AndroidRuntime(28635): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:943) 
09-27 23:47:11.015: E/AndroidRuntime(28635): at android.os.Handler.dispatchMessage(Handler.java:99) 
09-27 23:47:11.015: E/AndroidRuntime(28635): at android.os.Looper.loop(Looper.java:130) 
09-27 23:47:11.015: E/AndroidRuntime(28635): at android.app.ActivityThread.main(ActivityThread.java:3744) 
09-27 23:47:11.015: E/AndroidRuntime(28635): at java.lang.reflect.Method.invokeNative(Native Method) 
09-27 23:47:11.015: E/AndroidRuntime(28635): at java.lang.reflect.Method.invoke(Method.java:507) 
09-27 23:47:11.015: E/AndroidRuntime(28635): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860) 
09-27 23:47:11.015: E/AndroidRuntime(28635): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) 
09-27 23:47:11.015: E/AndroidRuntime(28635): at dalvik.system.NativeStart.main(Native Method) 
09-27 23:47:11.015: E/AndroidRuntime(28635): Caused by: java.lang.NullPointerException 
09-27 23:47:11.015: E/AndroidRuntime(28635): at java.io.StringReader.<init>(StringReader.java:46) 
09-27 23:47:11.015: E/AndroidRuntime(28635): at org.json.simple.JSONValue.parse(JSONValue.java:33) 
09-27 23:47:11.015: E/AndroidRuntime(28635): at com.mas.forcheksulotion.MainActivity.onCreate(MainActivity.java:57) 
09-27 23:47:11.015: E/AndroidRuntime(28635): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 
09-27 23:47:11.015: E/AndroidRuntime(28635): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1630) 
09-27 23:47:11.015: E/AndroidRuntime(28635): ... 11 more 

而我仍然不知道在android上使用Json我应该使用JSONArray或JSONObject或将Json解析为String?!

+0

'com.mas.forcheksulotion.MainActivity.onCreate(MainActivity.java:57)' - 什么是代码在这里...'MainActivity.java'在第57行。该值为空 –

+1

第二个请求 - 请向我们提供您的代码,以便我们可以帮助您获得该空值。 此外,我个人的建议,不要复制和粘贴任何解决方案将在这里报告解析一个JSON,如果你不读一点关于JSON。在这里你可以找到一个很好的总结/教程:http://www.elated.com/articles/json-basics/ 请记住,JSON基础知识与Android无关,但无论使用何种技术来管理它都是必要的。 。 – fasteque

+0

请发布你从服务器获得的数据,也就是'结果'。你有2个模块:从URL获取并解析。所以请确认第一,你有适当的Json(我认为 - 不)。之后,观察员你String –

回答

0

我发现这个问题

两种解决方案是伟大的,有用的,但我的错误是关于使用许可权。

我要补充这给AndroidManifest:

<uses-permission android:name="android.permission.INTERNET"></uses-permission> 
1

做到这一点..这是我的工作代码getiing从许多应用程序中使用url的json响应。

/** 
* This method used to get json from url. 
* 
* @param url 
*   represented url 
* @return represented {@link JSONObject} 
*/ 
public JSONObject getJSONFromUrl(String url) { 

    InputStream is = null; 
    JSONObject jObj = null; 
    try { 
     DefaultHttpClient httpClient = new DefaultHttpClient(); 
     HttpGet httpGet = new HttpGet(url); 
     HttpResponse httpResponse = httpClient.execute(httpGet); 

     HttpEntity httpEntity = httpResponse.getEntity(); 
     is = httpEntity.getContent(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
    try { 
     jObj = new JSONObject(getResponseBody(is)); 

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

/** 
* This method used to get response body. 
* 
* @param instream 
*   represented input stream 
* @return represented {@link String} 
* @throws IOException 
*    represented {@link IOException} 
* @throws ParseException 
*    represented {@link ParseException} 
*/ 
public String getResponseBody(final InputStream instream) throws IOException, ParseException { 

    if (instream == null) { 
     return ""; 
    } 

    StringBuilder buffer = new StringBuilder(); 

    BufferedReader reader = new BufferedReader(new InputStreamReader(instream, "utf-8")); 

    String line = null; 
    try { 
     while ((line = reader.readLine()) != null) { 
      buffer.append(line); 
     } 

    } finally { 
     instream.close(); 
     reader.close(); 
    } 
    System.out.println(buffer.toString()); 
    return buffer.toString(); 

}