java提供link;string转json

72 阅读1分钟

java提供link

JSONObject jsonObject = new JSONObject();
                    jsonObject.put("type", 1);
                    resp.setLink(new Link(5, surveyId, "COLLECT_PAGE", jsonObject.toJSONString()));

public Link(Integer type, String id, String url, String params) { this.type = type; this.id = id; this.url = url; this.isClear = isClear; this.params = params; }


处理这种请求link

"link":{ "id":null, "isClear":false, "params":"{"type":1}", "type":5, "url":"COLLECT_PAGE" }


所以前端这种json格式,Java处理可以  
[JSONObject](https://so.csdn.net/so/search?q=JSONObject&spm=1001.2101.3001.7020) 对象用来解决

"{"type":1}"

JSONObject jsonObject = new JSONObject();
                    jsonObject.put("type", 1);

```

**还有这样可以去接受前端传来json 但只给了你String**

```
List<KeyValueData> categoryList = JSONObject.parseArray(categoryInfo, KeyValueData.class);
                

```

string转json
-----------

首先引入依赖包,这里使用的是alibaba的[fastjson](https://so.csdn.net/so/search?q=fastjson&spm=1001.2101.3001.7020);

```
<!-- fastjson依赖 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.76</version>
</dependency>

```

**String转成JSON格式**

定义一个json格式的[字符串](https://so.csdn.net/so/search?q=%E5%AD%97%E7%AC%A6%E4%B8%B2&spm=1001.2101.3001.7020)  
String str= “{“code”:1,“data”:{“id”:9978,“name”:“sdklfj”}}”;

将字符串转换成json  
JSONObject jsonObject = JSONObject.parseObject(str);

取出data里的数据  
String code = jsonObject.getString(“code”);  
String data = jsonObject.getString(“data”);

```
jsonObject除了getString方法,还有getIntValue,getDoubleValue,getInteger等

```

System.out.println(code);  
//输出结果为:1

System.out.println(data);  
//输出结果为:{“name”:“sdklfj”,“id”:9978}

> 本文使用 [文章同步助手](https://juejin.cn/post/6940875049587097631) 同步