【Java】Java中将String转json对象

原文地址:https://blog.csdn.net/qq_17586821/article/details/53856606

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>

本文使用一个小例子展示在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中,大范围不能向小范围转。 
这里写图片描述

猜你喜欢

转载自blog.csdn.net/qq_30141957/article/details/79879612
今日推荐