【JAVA】转换Json,字符串,对象,List等

1.依赖com.alibaba.fastjson

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.54</version>
</dependency>

以下常见场景,自行选用

2.Json字符串——》JsonObject

JSONObject object=JSONObject.parseObject(s);

JsonObject——》Json字符串

String s=object.toString();

3.JsonObject获取JsonArray

JSONArray datas = object.getJSONArray("data");

4.JsonObject——》对象

YourBean bean=JSONObject.parseObject(data.toString(),YourBean.class)

5.对象——》Json字符串,接2可以——》JsonObject

String s=JSONObject.toJSONString(bean)

6.JsonArray——》对象List
=过时=

List<YourBean > collection=new ArrayList<>();
datas.forEach(d->collection.add(JSONObject.parseObject(d.toString(),YourBean.class)));
// collection即结果

=现在=

datas.toJavaList(XXX.class)

对象List——》JsonArray

JSONArray jsonArray=JSONArray.parseArray(JSONArray.toJSONString(collection))

猜你喜欢

转载自blog.csdn.net/g_y_x_/article/details/84837990
今日推荐