zoukankan      html  css  js  c++  java
  • 字符串 转换成 Java对象

    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=北京市西城区]

    要导包:

     <dependency>  
                <groupId>net.sf.json-lib</groupId>  
                <artifactId>json-lib</artifactId>  
                <version>2.2.3</version>  
                <classifier>jdk15</classifier>  
     </dependency>
  • 相关阅读:
    [luogu5665]划分
    [luogu5666]树的重心
    [bzoj1854]游戏
    [bzoj1853]幸运数字
    [bzoj2245]工作安排
    [bzoj1426]收集邮票
    [bzoj2396]神奇的矩阵
    [bzoj1858]序列操作
    [bzoj1863]皇帝的烦恼
    [bzoj1432]Function
  • 原文地址:https://www.cnblogs.com/yangxiaomei/p/9638836.html
Copyright © 2011-2022 走看看