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(); } }
輸出結果以下:java
{"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>git