字符串和json对象之间的转换关系——一定不要再导错包

添加依赖

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

 

 

一定不要导错包

 

 

字符串转换为json对象

import com.alibaba.fastjson.JSONObject;        // 需特别注意导包问题,因为一不小心就会导成其他包,然后爆红


@Test
void func(){
    String s = "{'name': 'Bruce', 'age': 24, 'sex': 'man'}";
    JSONObject jsonObject = JSONObject.parseObject(s);
    System.out.println(jsonObject);
}

 

json对象转换为字符串

// 注意:该场景一般出现在http请求中

resultString = EntityUtils.toString(response.getEntity(), "UTF-8");

 

 

// 常见场景

@Test
void func() throws JSONException {

    JSONObject jsonObject = new JSONObject();
    jsonObject.put("name", "jfdk");
    jsonObject.put("sex", 45);
    jsonObject.put("age", 45);
    System.out.println(jsonObject.toString());
    System.out.println(JSONObject.parseObject(jsonObject.toString()).get("sex"));

}

 

posted @ 2023-03-31 15:40  先娶国王后取经  阅读(35)  评论(0编辑  收藏  举报