Java中将String转json对象

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.junit.Test;
 
public class SimpleJson {
 
    @Test
    public void stringToJson() {
        String str = "{" + "\"" + "latitude" + "\"" + ":" + 30.23 + "," + "\"" + "longitude"
                + "\"" + ":" + 114.57 + "}";
        System.out.println(str + "\n" + str.getClass());
        try {
            JSONObject jsonObj = (JSONObject)(new JSONParser().parse(str));
            System.out.println(jsonObj.toJSONString() + "\n" + jsonObj.getClass());
            /*float longitude = (float)jsonObj.get("longitude");
            System.out.println(longitude);*/
            double latitude = (double)jsonObj.get("latitude");
            System.out.println(latitude);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
 

输出结果如下:

{"latitude":30.23,"longitude":114.57}
 
class java.lang.String
 
{"latitude":30.23,"longitude":114.57}
 
class org.json.simple.JSONObject
 

 

maven项目中,需要在pom.xml文件的<dependencies>标签下加上对JSONsimple的依赖,如下
  <!-- https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple -->
<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version>
</dependency>

posted @ 2019-01-09 17:04  ^sun^  阅读(60340)  评论(0编辑  收藏  举报