Json转换 在java中的应用

Json转换辅助类比较多,比如谷歌的Gson,阿里的FastJson,Jackson、net.sf.json等等

用了一圈后,本人还是比较推荐用net.sf.json

这里就介绍一下net.sf.json 的简单使用

1 maven配置如下

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

有时引用会报:has broken path 的错误,一版都是配置缺了点引起的,改成如下即可:

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

2 Object转String字符串

       //将JavaBean转换为JSONObject
        Student student = new Student("wln", "22");
        JSONObject jsonObject = JSONObject.fromObject(student);
        System.out.println( jsonObject);

3 String转Object

       //将JSONString转换为JSONObject
        String jsonStr = "{"name":"nana","age":"33"}";
        JSONObject jsonObject1 = JSONObject.fromObject(jsonStr);
        Student stu = (Student)JSONObject.toBean(jsonObject1,Student.class);

4 String转Object后,可以直接获取里面的key值

//获取数组
JSONArray array=obj.getJSONArray("trans_result");
//也可获取string的字段
String value=obj.getString("key");
//还有其它不少的封装好的方法

具体的使用方法可以自行百度,

如:https://www.cnblogs.com/nananana/p/9263708.html

原文地址:https://www.cnblogs.com/fj99/p/11593797.html