将Json解析为String [英] Parse Json to String

查看:199
本文介绍了将Json解析为String的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将Json解析为字符串,以将其显示在listView上.我搜索并阅读了很多文章和问题,但找不到解决方法

I want to parse Json to string, to show it on a listView. I search and read lots of Articles and questions but I can't find the solution

我已经尝试过以下解析器JSON: Android JSON解析教程

I've tried this parser JSON From: 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;

    }
}

另外一个来自如何在Android中解析JSON

And another one from 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时(例如:

but in both of them when I use a string Json , everything is ok , but when I want to Read Json from a Web API (ex: http://api.androidhive.info/contacts/) this errors comes to me:

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吗?!

And still I don't know for using Json on android I should work with JSONArray , or JSONObject or parse Json to String ?!

推荐答案

我发现了问题

两个解决方案都是很好且有用的,但我的错误是关于使用权限.

two solutions is great and useful , but my mistake was about the uses-permission.

我应该将此添加到AndroidManifest中:

i should add this to the AndroidManifest :

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

这篇关于将Json解析为String的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆