【问题标题】:Sending and Parsing JSON Objects in Android [closed]在 Android 中发送和解析 JSON 对象 [关闭]
【发布时间】:2026-01-21 19:10:01
【问题描述】:

我想以 JSON 对象的形式向服务器发送消息并解析来自服务器的 JSON 响应。

JSON 对象示例

{
  "post": {
    "username": "John Doe",
    "message": "test message",
    "image": "image url",
    "time":  "current time"
  }
}

我正在尝试通过逐个属性手动解析 JSON。有没有我可以使用的库/实用程序来简化这个过程?

【问题讨论】:

  • 该网址不再可用...您能更新一下吗?
  • 这里有一个详细的例子:Android – JSON Parsing example
  • @Paresh Mayani & @primpap .. 我知道我们可以使用 get 方法从服务器接收的 JSON 填充来自服务器的数据,我很满意....但是如果我们使用post 方法将数据发送到服务器,我们是否再次将数据作为 JSON 发送,我指的是 primpap 问题的引用“我想以 JSON 对象的形式将消息发送到 Django 服务器”.....我我在服务器上使用 Mysql .... 还是我发送 JSON 对象? ...您能否向我澄清此信息....或任何有助于我理解该概念的链接都会有所帮助,谢谢

标签: android json parsing


【解决方案1】:

如果数据有明确的结构,GSON 是最容易使用的方法。

下载gson

将其添加到引用的库中。

package com.tut.JSON;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class SimpleJson extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        String jString = "{\"username\": \"tom\", \"message\": \"roger that\"}  ";


        GsonBuilder gsonb = new GsonBuilder();
        Gson gson = gsonb.create();
        Post pst;

        try {
            pst = gson.fromJson(jString,  Post.class);

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

Post 类代码

package com.tut.JSON;

public class Post {

    String message;
    String time;
    String username;
    Bitmap icon;
}

【讨论】:

  • 为了它的价值,代码可以被简化:JSONObject 转换是不必要的。而setter和getter对于GSon来说是可选的;可以根据需要添加,但不是绝对必要的。
  • 只是为了澄清 StaxMan 的评论。您的示例采用 jString,将其转换为 JSONObject,然后将其转换回字符串以供 gson 读取。只需使用 pst = gson.fromJson(jString, Post.class)。我相信这也将摆脱对 try-catch 的需要。正如 StaxMan 还指出的那样, Post.class 中的 setter 和 getter 没有任何价值。纠正您的示例对其他人会有所帮助。
  • 我从答案中删除了双重转换部分
【解决方案2】:

有不同的开源库,您可以使用它们来解析 json。

org.json :- 如果你想读取或写入 json,那么你可以使用这个库。 首先创建 JsonObject :-

JSONObject jsonObj = new JSONObject(<jsonStr>);

现在,使用这个对象来获取你的值:-

String id = jsonObj.getString("id");

你可以看到完整的例子here

Jackson databind :- 如果你想将你的 json 绑定并解析到特定的 POJO 类,那么你可以使用 jackson-databind 库,这会将你的 json 绑定到 POJO 类:-

ObjectMapper mapper = new ObjectMapper();
post= mapper.readValue(json, Post.class);

你可以看到完整的例子here

【讨论】:

    【解决方案3】:

    你只需要导入这个

       import org.json.JSONObject;
    
    
      constructing the String that you want to send
    
     JSONObject param=new JSONObject();
     JSONObject post=new JSONObject();
    

    我使用两个对象,因为你可以在另一个对象中有一个 jsonObject

    post.put("username(here i write the key)","someusername"(here i put the value);
    post.put("message","this is a sweet message");
    post.put("image","http://localhost/someimage.jpg");
    post.put("time":  "present time");
    

    然后我把post json放在另一个这样的里面

      param.put("post",post);
    

    这是我用来发出请求的方法

     makeRequest(param.toString());
    
    public JSONObject makeRequest(String param)
    {
        try
        {
    

    设置连接

            urlConnection = new URL("your url");
            connection = (HttpURLConnection) urlConnection.openConnection();
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-type", "application/json;charset=UTF-8");
            connection.setReadTimeout(60000);
            connection.setConnectTimeout(60000);
            connection.connect();
    

    设置输出流

            dataOutputStream = new DataOutputStream(connection.getOutputStream());
    

    我用它在 logcat 中查看我发送的内容

            Log.d("OUTPUT STREAM  " ,param);
            dataOutputStream.writeBytes(param);
            dataOutputStream.flush();
            dataOutputStream.close();
    
            InputStream in = new BufferedInputStream(connection.getInputStream());
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            result = new StringBuilder();
            String line;
    

    这里构造了字符串

            while ((line = reader.readLine()) != null)
            {
                result.append(line);
            }
    

    我使用这个日志来查看响应中的内容

             Log.d("INPUTSTREAM: ",result.toString());
    

    使用包含服务器响应的字符串实例化一个 json

            jResponse=new JSONObject(result.toString());
    
        }
        catch (IOException e) {
            e.printStackTrace();
            return jResponse=null;
        } catch (JSONException e)
        {
            e.printStackTrace();
            return jResponse=null;
        }
        connection.disconnect();
        return jResponse;
    }
    

    【讨论】:

    • 提前感谢您的宝贵时间。我使用您的代码将 base64 编码的字符串发送到 django 服务器,但是当我单击按钮发送到服务器时,APP 崩溃了。你能帮我解决这个问题吗?
    【解决方案4】:

    这是 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;
    
        }
    

    注意:sdk 23 不再支持 DefaultHttpClient,因此建议在此代码中使用目标 sdk 21。

    【讨论】:

      【解决方案5】:

      尽管用户已经提供了很好的答案,例如鼓励使用 GSON 等。我想建议使用org.json。它包括大部分 GSON 功能。它还允许您将 json 字符串作为参数传递给它的 JSONObject,它会处理其余部分,例如:

      JSONObject json = new JSONObject("some random json string");

      这个功能使它成为我个人的最爱。

      【讨论】:

        【解决方案6】:

        我很惊讶这些没有被提及:但是 GSon 和 Jackson 使用起来更方便,而不是使用 json.org 的小包的简单的手动过程。所以:

        因此,您实际上可以绑定到自己的 POJO,而不是一些半途而废的树节点或列表和映射。 (至少 Jackson 也允许绑定到这些东西(也许 GSON 也可以,不确定)、JsonNode、Map、List,如果你真的想要这些而不是“真实”对象)

        2014 年 3 月 19 日编辑:

        另一个新的竞争者是Jackson jr 库:它使用与 Jackson (jackson-core) 相同的快速流解析器/生成器,但数据绑定部分很小 (50kB)。功能更受限制(没有注释,只有常规 Java Bean),但性能方面应该很快,初始化(第一次调用)开销也非常低。 所以它可能是一个不错的选择,尤其是对于较小的应用程序。

        【讨论】:

        • GSON +1。我们在 Android 应用中特别使用了 GSON 的流媒体支持 sites.google.com/site/gson/streaming
        • FWIW,Jackson 也有流媒体 API:wiki.fasterxml.com/JacksonStreamingApi
        • 对于 GSON 流媒体也是 +1。最初实现了 Jackson 流,但尽管在调试版本中起作用,ProGuard 产生了大量错误,并且发布版本导致难以追踪的崩溃。我确信这与 Jackson 无关,但它让我改用 GSON,它工作得很好,只需要额外的 14kB 就可以流式传输。
        • 对于愚蠢的不可预测的 json 混合字符串和列表例如:["toto", "tata", ["monty", ["tor", "python"]]]? (一种需要递归函数来使用它的数据结构)
        【解决方案7】:

        如果您正在寻找 android 中的快速 json 解析,那么我建议您使用免费提供的工具。

        JSON Class Creator tool

        它是免费使用的,它可以在一两秒内创建你所有的 json 解析类.. :D

        【讨论】:

          【解决方案8】:

          其他答案提到了 Jackson 和 GSON - 适用于 Android 的流行附加 JSON 库,以及 json.org,Android 中包含的基本 JSON 包。

          但我认为还值得注意的是,Android 现在拥有自己的全功能 JSON API。

          这是在 Honeycomb:API 级别 11 中添加的。

          这包括
          - android.util.JsonReader:docssource
          - android.util.JsonWriter:docs,和source

          我还将添加一个额外的考虑因素,让我回到 Jackson 和 GSON:我发现使用 3rd 方库而不是 android.* 包很有用,因为这样我编写的代码可以在客户端和服务器之间共享。这与 JSON 之类的东西特别相关,您可能希望在一端将数据序列化为 JSON 以发送到另一端。对于这样的用例,如果您在两端都使用 Java,则有助于避免引入 android.* 依赖项。

          或者我想可以获取相关的 android.* 源代码并将其添加到您的服务器项目中,但我还没有尝试过...

          【讨论】:

            【解决方案9】:

            JSON 没有任何意义。花括号用于“对象”(关联数组),方括号用于没有键的数组(数字索引)。至于在 Android 中使用它,SDK 中包含了现成的类(无需下载)。

            查看这些课程: http://developer.android.com/reference/org/json/package-summary.html

            【讨论】:

            • 我想你的意思是花括号而不是尖括号!
            【解决方案10】:

            您可以使用org.json.JSONObjectorg.json.JSONTokener。您不需要任何外部库,因为这些类随 Android SDK 提供

            【讨论】:

            • 糟糕!我错过了。事实上,它们就是网站上的 org.json 库。
            • 这是我使用的,它就像一个魅力。
            • 如果能给出一个例子或链接就太好了。这样更容易学习。 :)
            • 更方便,编写代码更少:一两行而不是几十行。
            【解决方案11】:

            您可以从http://json.org(Json-lib 或 org.json)下载一个库并使用它来解析/生成 JSON

            【讨论】: