大家好,又见面了,我是你们的朋友全栈君。
本文使用一个小例子展示在java中怎样将一个JSON格式的字符串转化为JSONObject对象。注意,我们使用的是 org.json.simple.JSONObject;
package com.qs.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
30.23
题外话:
下面是被注释的那部分报的错:浮点数的字面量是double,而在java中,大范围不能向小范围转。
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/172478.html原文链接:https://javaforall.cn