• 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>

  • 相关阅读:
    Spring MVC的常用注解(一)
    Spring MVC接口实例
    MVC模式和Spring MVC初识
    Hbase数据结构和shell操作
    Hbase的安装和配置
    ZooKeeper安装、配置和使用
    hadoop的安装和配置
    VMware Workstation安装CentOS 7和开发环境
    Java基础-内部类
    SSM三大框架整合
  • 原文地址:https://www.cnblogs.com/sunBinary/p/10245541.html
Copyright © 2020-2023  润新知