将 JSON 字符串转换为 Java Object 或 HashMap
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2553535/
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
Convert JSON String to Java Object or HashMap
提问by Priyank
I am writing an android app. I want to pass some data across the intents/activities and I feel that a conversion to and from JSON is probably a more optimal way at this point. I am able to convert a java hashmap to a json string successfully using JSONObject support.
我正在编写一个 android 应用程序。我想在意图/活动之间传递一些数据,我觉得在这一点上,与 JSON 之间的转换可能是更理想的方式。我能够使用 JSONObject 支持成功地将 java hashmap 转换为 json 字符串。
However i need to convert back this JSON string to a java object or a hashmap. What is the best way to go about it.
但是我需要将此 JSON 字符串转换回 java 对象或哈希图。最好的方法是什么。
Is parcelable really a change worth doing; if I have simple 5 field object? What are the other ways to transfer data between intents.
Parcelable 真的是一个值得做的改变;如果我有简单的 5 个字段对象?在意图之间传输数据的其他方法是什么。
Cheers
干杯
回答by BalusC
I recommend to pick Gsonfor that. It has excellent support for generics and fullworthy Javabeans and really eases the conversion task. In this answeryou can find an example to convert a Map<String, String>to JSON and vice versa and in this answeranother example to convert a JSON string to a fullworthy Javabean (from Javabean to JSON is pretty simple with gson.toJson(bean).
我建议为此选择Gson。它对泛型和完全有价值的 Javabeans 有很好的支持,并真正简化了转换任务。在这个答案,你可以找到一个例子,一个转换Map<String, String>到JSON,反之亦然,并在此答案的另一个例子,一个JSON字符串转换为fullworthy的Javabean(从JavaBean来JSON是非常简单的使用gson.toJson(bean)。
Other ways to transfer data are XML and serialization, both which have much more overhead than JSON.
其他传输数据的方法是 XML 和序列化,两者的开销都比 JSON 多得多。
回答by alexanderblom
Why not use Bundleas your Map? It can be put in an Intenteasily and is basically a glorified typesafe HashMap.
为什么不用Bundle作你的Map?它可以Intent很容易地放入并且基本上是一个美化的 typesafe HashMap。
If you still need to use JSON I would recommend Hymanson. It's easy and fast (faster than GSON) for converting to and from Java objects (including Maps)
如果您仍然需要使用 JSON,我会推荐Hymanson。与 Java 对象(包括Maps)之间的转换既简单又快速(比 GSON 快)
回答by yanchenko
You can pass Serializables with Intents, no need for JSON.
你可以Serializable用Intents传递s ,不需要 JSON。
回答by Elliott Hughes
JSON is a particularly bad choice if you have numeric data... it'll mangle anything that can't be represented as a double (and even some double values). except where you have to communicate with JavaScript, you should avoid JSON.
如果您有数字数据,JSON 是一个特别糟糕的选择......它会破坏任何不能表示为双精度(甚至一些双精度值)的东西。除了必须与 JavaScript 通信的地方,您应该避免使用 JSON。

