在 Android 中发送和解析 JSON 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2818697/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sending and Parsing JSON Objects in Android
提问by Primal Pappachan
I would like to send messages in the form of JSON objects to a server and parse the JSON response from the server.
我想以 JSON 对象的形式将消息发送到服务器并解析来自服务器的 JSON 响应。
Example of JSON object
JSON 对象示例
{
"post": {
"username": "John Doe",
"message": "test message",
"image": "image url",
"time": "current time"
}
}
I am trying to parse the JSON manually by going attribute by attribute. Is there any library/utility I can use to make this process easier?
我试图通过逐个属性来手动解析 JSON。我可以使用任何库/实用程序来简化此过程吗?
采纳答案by StaxMan
I am surprised these have not been mentioned: but instead of using bare-bones rather manual process with json.org's little package, GSon and Hymanson are much more convenient to use. So:
我很惊讶这些没有被提及:但是,与使用 json.org 的小包的基本流程而不是手动流程不同,GSon 和 Hymanson 使用起来要方便得多。所以:
So you can actually bind to your own POJOs, not some half-assed tree nodes or Lists and Maps. (and at least Hymanson allows binding to such things too (perhaps GSON as well, not sure), JsonNode, Map, List, if you really want these instead of 'real' objects)
因此,您实际上可以绑定到您自己的 POJO,而不是一些半途而废的树节点或列表和映射。(至少Hyman逊也允许绑定到这些东西(也许 GSON 也是如此,不确定)、JsonNode、Map、List,如果你真的想要这些而不是“真实”对象)
EDIT 19-MAR-2014:
编辑 2014 年 3 月 19 日:
Another new contender is Hymanson jrlibrary: it uses same fast Streaming parser/generator as Hymanson (Hymanson-core
), but data-binding part is tiny (50kB). Functionality is more limited (no annotations, just regular Java Beans), but performance-wise should be fast, and initialization (first-call) overhead very low as well.
So it just might be good choice, especially for smaller apps.
另一个新的竞争者是Hymanson jr库:它使用与 Hymanson ( Hymanson-core
)相同的快速流解析器/生成器,但数据绑定部分很小 (50kB)。功能更有限(没有注释,只有普通的 Java Beans),但性能方面应该很快,并且初始化(第一次调用)开销也非常低。所以它可能是不错的选择,尤其是对于较小的应用程序。
回答by Valentin Golev
You can use org.json.JSONObjectand org.json.JSONTokener. you don't need any external libraries since these classes come with Android SDK
您可以使用org.json.JSONObject和org.json.JSONTokener。您不需要任何外部库,因为这些类随 Android SDK 一起提供
回答by Primal Pappachan
GSON is easiest to use and the way to go if the data have a definite structure.
如果数据具有明确的结构,GSON 是最容易使用的方法。
Download gson.
下载gson。
Add it to the referenced libraries.
将其添加到引用的库中。
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();
}
}
}
Code for Post class
Post 类代码
package com.tut.JSON;
public class Post {
String message;
String time;
String username;
Bitmap icon;
}
回答by www.9android.net
This is the JsonParser class
这是 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;
}
Note: DefaultHttpClient is no longer supported by sdk 23, so it is advisable to use target sdk 21 with this code.
注意:sdk 23 不再支持 DefaultHttpClient,因此建议使用带有此代码的目标 sdk 21。
回答by Rich
There's not really anything to JSON. Curly brackets are for "objects" (associative arrays) and square brackets are for arrays without keys (numerically indexed). As far as working with it in Android, there are ready made classes for that included in the sdk (no download required).
JSON 真的没有任何东西。大括号用于“对象”(关联数组),方括号用于没有键的数组(数字索引)。就在 Android 中使用它而言,sdk 中包含现成的类(无需下载)。
Check out these classes: http://developer.android.com/reference/org/json/package-summary.html
查看这些类:http: //developer.android.com/reference/org/json/package-summary.html
回答by Tom
Other answers have noted Hymanson and GSON - the popular add-on JSON libraries for Android, and json.org, the bare-bones JSON package that is included in Android.
其他答案提到了 Hymanson 和 GSON——Android 的流行附加 JSON 库,以及 json.org,Android 中包含的基本 JSON 包。
But I think it is also worth noting that Android now has its own full featured JSON API.
但我认为还值得注意的是,Android 现在拥有自己的全功能 JSON API。
This was added in Honeycomb: API level 11.
这是在 Honeycomb:API 级别 11 中添加的。
This comprises
- android.util.JsonReader: docs, and source
- android.util.JsonWriter: docs, and source
这包括
- android.util.JsonReader: docs和source
- android.util.JsonWriter: docs和source
I will also add one additional consideration that pushes me back towards Hymanson and GSON: I have found it useful to use 3rd party libraries rather then android.* packages because then the code I write can be shared between client and server. This is particularly relevant for something like JSON, where you might want to serialize data to JSON on one end for sending to the other end. For use cases like that, if you use Java on both ends it helps to avoid introducing android.* dependencies.
我还将添加一个额外的考虑因素,使我回到 Hymanson 和 GSON:我发现使用 3rd 方库而不是 android.* 包很有用,因为这样我编写的代码可以在客户端和服务器之间共享。这与 JSON 之类的内容特别相关,您可能希望在一端将数据序列化为 JSON,以便发送到另一端。对于这样的用例,如果您在两端都使用 Java,则有助于避免引入 android.* 依赖项。
Or I guess one could grab the relevant android.* source code and add it to your server project, but I haven't tried that...
或者我想可以获取相关的 android.* 源代码并将其添加到您的服务器项目中,但我还没有尝试过...
回答by Gaurav Vaish
You can download a library from http://json.org(Json-lib or org.json) and use it to parse/generate the JSON
您可以从http://json.org(Json-lib 或 org.json)下载一个库并使用它来解析/生成 JSON
回答by Edgardo Alvarez
you just need to import this
你只需要导入这个
import org.json.JSONObject;
constructing the String that you want to send
JSONObject param=new JSONObject();
JSONObject post=new JSONObject();
im using two object because you can have an jsonObject within another
我使用了两个对象,因为你可以在另一个对象中有一个 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");
then i put the post json inside another like this
然后我把post json放在另一个像这样的里面
param.put("post",post);
this is the method that i use to make a request
这是我用来提出请求的方法
makeRequest(param.toString());
public JSONObject makeRequest(String param)
{
try
{
setting the connection
设置连接
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();
setting the outputstream
设置输出流
dataOutputStream = new DataOutputStream(connection.getOutputStream());
i use this to see in the logcat what i am sending
我用它在 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;
here the string is constructed
这里构造了字符串
while ((line = reader.readLine()) != null)
{
result.append(line);
}
i use this log to see what its comming in the response
我使用此日志查看响应中的内容
Log.d("INPUTSTREAM: ",result.toString());
instancing a json with the String that contains the server response
使用包含服务器响应的字符串实例化 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;
}
回答by Akash
There are different open source libraries, which you can use for parsing json.
有不同的开源库,您可以使用它们来解析 json。
org.json :-If you want to read or write json then you can use this library. First create JsonObject :-
org.json :-如果你想读或写 json 那么你可以使用这个库。首先创建 JsonObject :-
JSONObject jsonObj = new JSONObject(<jsonStr>);
Now, use this object to get your values :-
现在,使用此对象获取您的值:-
String id = jsonObj.getString("id");
You can see complete example here
您可以在此处查看完整示例
Hymanson databind :-If you want to bind and parse your json to particular POJO class, then you can use Hymanson-databind library, this will bind your json to POJO class :-
Hymanson databind :-如果你想将你的 json 绑定和解析到特定的 POJO 类,那么你可以使用 Hymanson-databind 库,这会将你的 json 绑定到 POJO 类:-
ObjectMapper mapper = new ObjectMapper();
post= mapper.readValue(json, Post.class);
You can see complete example here
您可以在此处查看完整示例
回答by sachin
if your are looking for fast json parsing in android than i suggest you a tool which is freely available.
如果您正在寻找 android 中的快速 json 解析,我建议您使用免费提供的工具。
It's free to use and it's create your all json parsing class within a one-two seconds.. :D
它可以免费使用,并且可以在一两秒内创建您的所有 json 解析类.. :D