转换JSON字符串到Java对象或HashMap的字符串、对象、JSON、HashMap

2023-09-06 06:32:59 作者:勿忘与他旳情

我写一个Android应用程序。我希望在整个意图/活动传递一些数据和我觉得转换和从JSON是可能在这一点上更优化的方式。我能够在Java哈希映射转换为一个JSON字符串成功地利用JSONObject的支持。

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.

不过,我需要这个JSON字符串转换回Java对象或一个HashMap。什么是去它的最好方式。

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.

时parcelable真正的变化值得做;如果我有简单的5场的对象?有什么其他方式来意图之间传输数据。

Is parcelable really a change worth doing; if I have simple 5 field object? What are the other ways to transfer data between intents.

干杯

推荐答案

我建议挑选 GSON 为。它有一个泛型和fullworthy的Javabean良好的支持,真正减轻了转换任务。在this回答你可以找到一个例子来转换地图<字符串,字符串> 来JSON,反之亦然,并在这个答案另一个例子,一个JSON字符串转换为fullworthy的Javabean(从JavaBean来JSON是pretty简单与 gson.toJson(豆)

I recommend to pick Gson for that. It has excellent support for generics and fullworthy Javabeans and really eases the conversion task. In this answer you can find an example to convert a Map<String, String> to JSON and vice versa and in this answer another example to convert a JSON string to a fullworthy Javabean (from Javabean to JSON is pretty simple with gson.toJson(bean).

其他方式来传输数据是XML和序列化,这两者比JSON多的开销。

Other ways to transfer data are XML and serialization, both which have much more overhead than JSON.