zoukankan      html  css  js  c++  java
  • json转对象

    1,引入依赖

       <dependency>
                <groupId>net.sf.json-lib</groupId>
                <artifactId>json-lib</artifactId>
                <version>2.4</version>
                <classifier>jdk15</classifier>
       </dependency>

    2,

    public static void jsonStrToJava(){
            //定义两种不同格式的字符串
            String objectStr="{"name":"JSON","age":"24","address":"北京市西城区"}";
            String arrayStr="[{"name":"JSON","age":"24","address":"北京市西城区"}]";
        
            //1、使用JSONObject
            JSONObject jsonObject=JSONObject.fromObject(objectStr);
            Student stu=(Student)JSONObject.toBean(jsonObject, Student.class);
            
            //2、使用JSONArray
            JSONArray jsonArray=JSONArray.fromObject(arrayStr);
            //获得jsonArray的第一个元素
            Object o=jsonArray.get(0);
            JSONObject jsonObject2=JSONObject.fromObject(o);
            Student stu2=(Student)JSONObject.toBean(jsonObject2, Student.class);
            System.out.println("stu:"+stu);
            System.out.println("stu2:"+stu2);
            
        }

    打印结果为:

    stu:Student [name=JSON, age=24, address=北京市西城区]
    stu2:Student [name=JSON, age=24, address=北京市西城区]
  • 相关阅读:
    代码发布一
    Qt之QThread(深入理解)
    Azure 云助手正式发布
    Qt之自定义控件(开关按钮)
    CentOS 7.x安装配置
    CSDN中的Bug
    Qt之findChild
    CentOS 6.x启动时网卡eth0未激活
    CentOS 6.x安装配置
    CentOS所有下载
  • 原文地址:https://www.cnblogs.com/cailijuan/p/8709633.html
Copyright © 2011-2022 走看看