0

我在 mvc 中创建了一个 json 结果,我正在构建一个 Android 应用程序来获取 json 结果。这就是我的 json 结果的样子

{"name":"Mr. Spock","gender":"Male"}

这是我的控制器

public ActionResult Index()
        {

            var result = new { name = "Mr. Spock", gender = "Male" };
            return Json(result, JsonRequestBehavior.AllowGet);

        }

这是我在android中使用的

// Creating JSON Parser instance
JSONParser jParser = new JSONParser();

// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);

JSONParser 类

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;

    }
}

我有一个声明的变量 url。每次调试时,json 变量都没有任何值,并显示“评估期间出现错误”

有小费的吗?我尝试与 Gson 合作,但没有成功

亲切的问候

4

1 回答 1

0

我会给你一些 Gson 的代码。它确实比内置的 JSON 解析代码更容易使用。这是使用您的 JSON 的最小示例。

人.类:

package com.example.tutorial.models;

import com.google.gson.annotations.SerializedName;

public class Person {

    @SerializedName("gender")
    public String gender = "";

    @SerializedName("name")
    public String name = "";
}

只有当您的变量和 JSON 名称不同时,注释才真正需要,但我倾向于始终包含它们,因为它强化了它们来自 JSON。

反序列化:

Gson gson = new GsonBuilder().create();
Person person = gson.fromJson(json, Person.class);

真的就是这么简单。如果这不起作用,请记录来自 Web 服务器的结果并确保它确实是您期望的有效 JSON 字符串。

我确实有一个问题,你的 AsyncTask 在哪里?您尝试在 UI 线程中打开与 Web 服务器的连接肯定会导致 NetworkOnMainThreadException。我创建了一个库来在 Android 上进行 RESTful 调用。它在 BSD 下获得许可,因此请随意将其用作指南或直接使用它:https ://github.com/nedwidek/Android-Rest-API

于 2013-05-18T23:06:09.210 回答