Json复杂数组类型转换和入门(Json-Lib、Org.Json、Jackson、Gson、FastJson)

       JSON和字符串相互转换最主要是jar的引入,很多时候无法转换都是导入的jar不符合当前方法。目前主要有五种常用的jar:org.json、net.sf(Json-Lib)、fastJson、Gson、Jackson。转换出错了,第一时间:看你目前导入的jar是哪个!

以下内容分为两部分,较复杂的json转换和json入门。

 

[{"xxx":"xxx","xxx":"xxx"}]较复杂类型的转换:

下面示例使用org.jsongson(较简单)这两个的转换方法,转换的内容格式如数组里面还有各种对象:[{"xxx":"xxx","xxx":"xxx"}],比较复杂的。如果只想json入门,区分这几个jar的使用,看简单的Json-Lib、Org.Json、Jackson、Gson、FastJson的demo,就跳过这一段,拉到下面

一:org.json,maven依赖如下

<dependency>
      <groupId>org.json</groupId>
      <artifactId>json</artifactId>
      <version>20170516</version>
</dependency>

 

1、java后台转换的json字符串,存进数据库

先定义一个:

List<Map<String, Object>> listMap

用map存key,value,然后list.add()每一个map,最后再调用json.tojson(String)转为String存到数据库。这样子存是一个数组json:[{"xxx":"xxx"},{"xxx":"xxx"}],如果只是存纯json,没有数组,格式如:{"xxx":"xxx"},{"xxx":"xxx"},就只需要定义

Map<String, Object>

然后就可以存到数据库了。

 

2、Java后台从数据库取出json字符串,然后提供给Jsp读取json,直接点出来属性名

从数据库取出来的json串已经被改为String了,所以要先把String转json,json再转回listMap,这个listMap就可以在页面中通过key-value的关系直接点出来了。

/**
    * 把附件信息从String--Json--ListMap
    * @param arr
    * @return
    */
public  List<Map<String,Object>> JsonToListMap(String arr){
       JSONArray jsonArray =new JSONArray(arr);
       //JSONArray遍历
       List<Map<String,Object>> listMap = new ArrayList<Map<String,Object>>();
       for(int i=0; i<jsonArray.length(); i++) {
           Map<String, Object> map = new HashMap<String, Object>();
           map.put("id", jsonArray.getJSONObject(i).get("id"));
           map.put("name", jsonArray.getJSONObject(i).get("name"));
           listMap.add(map);
       }
       return listMap;
}

 

二、Gson(较简单)

maven依赖

<dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.8.1</version>
</dependency>

转换方式: 

//com.google.gson.Gson
//Gson转实体类比较好用

//把List转为JSON格式的字符串
Gson gs = new Gson();
List<FileInfo> fileInfos = new ArrayList<FileInfo>();
fileInfos.add(fileInfo);
String listStr = gs.toJson(fileInfos);


//把json字符串转回实体类对象
Gson gs = new Gson();
List<FileInfo> jsonListObject = gs.fromJson(listJson, new TypeToken<List<FileInfo>>(){}.getType());//把JSON格式的字符串转为List
for (FileInfo p : jsonListObject) {
   System.out.println("把JSON格式的字符串转为List"+p.toString());
}

 

简单的转换,json入门:

测试用例,一个User类,属性name,age,location。重写toString()。

public class User {
    private String name;
    private Integer age;
    private String location;

    public User() {
    }
    public User(String name) {
        this.name = name;
    }
    public User(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
    public User(String name, Integer age, String location) {
        this.name = name;
        this.age = age;
        this.location = location;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    public String getLocation() {
        return location;
    }
    public void setLocation(String location) {
        this.location = location;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", location='" + location + '\'' +
                '}';
    }
}

 

1、Json-Lib:JSONObject json = JSONObject.fromObject(string转json);
maven依赖如下,需注意<classifier>jdk15</classifier>,jar包区分jdk1.3和jdk1.5版本。当然你也可以使用6个jar的版本,那6个jar分别为:json-lib-2.3-jdk15.jar、commons-lang-2.4.jar、ezmorph-1.0.6.jar、commons-logging-1.1.1.jar、commons-collections-3.1.jar、commons-beanutils-1.8.0.jar,下载链接:https://download.csdn.net/download/qq_36688143/10165753

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



测试demo

import net.sf.json.JSONObject;

public class JsonLibDemo {

    public static void main(String[] args) {
        //创建测试object
        User user = new User("李宁",24,"北京");
        System.out.println(user);

        //转成json字符串
        JSONObject jsonObject = JSONObject.fromObject(user);
        String json = jsonObject.toString();
        System.out.println(json);

        //json字符串转成对象
        JSONObject jsonObject1 = JSONObject.fromObject(json);
        User user1 = (User) JSONObject.toBean(jsonObject1,User.class);
        System.out.println(user1);
    }
}


2、org.json:JSONObject json = new JSONObject(string转json);
maven依赖如下

    <dependency>
      <groupId>org.json</groupId>
      <artifactId>json</artifactId>
      <version>20170516</version>
    </dependency>



测试demo

import org.json.JSONObject;

public class OrgJsonDemo {
    public static void main(String[] args) {
        //创建测试object
        User user = new User("李宁",24,"北京");
        System.out.println(user);

        //转成json字符串
        String json = new JSONObject(user).toString();
        System.out.println(json);

        //json字符串转成对象
        JSONObject jsonObject = new JSONObject(json);
        String name = jsonObject.getString("name");
        Integer age = jsonObject.getInt("age");
        String location = jsonObject.getString("location");
        User user1 = new User(name,age,location);
        System.out.println(user1);
    }
}


3、Jackson
maven依赖

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.0</version>
    </dependency>



测试demo

import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonDemo {
    public static void main(String[] args) {
        //创建测试object
        User user = new User("李宁",24,"北京");
        System.out.println(user);

        //转成json字符串
        ObjectMapper mapper = new ObjectMapper();
        try {
            String json = mapper.writeValueAsString(user);
            System.out.println(json);


            //json字符串转成对象
            User user1 = mapper.readValue(json,User.class);
            System.out.println(user1);

        } catch (java.io.IOException e) {
            e.printStackTrace();
        }
    }
}


4、Gson
maven依赖

<dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.8.1</version>
</dependency>



测试demo

import com.google.gson.Gson;

public class GsonDemo {
    public static void main(String[] args) {
        //创建测试object
        User user = new User("李宁",24,"北京");
        System.out.println(user);

        //转成json字符串
        Gson gson = new Gson();
        String json = gson.toJson(user);
        System.out.println(json);

        //json字符串转成对象
        User user1 = gson.fromJson(json,User.class);
        System.out.println(user1);
    }
}


5、FastJson
maven依赖

 <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.37</version>
</dependency>



测试demo

import com.alibaba.fastjson.JSON;

public class FastJsonDemo {
    public static void main(String[] args) {
        //创建测试object
        User user = new User("李宁",24,"北京");
        System.out.println(user);

        //转成json字符串
        String json = JSON.toJSON(user).toString();
        System.out.println(json);

        //json字符串转成对象
        User user1 = JSON.parseObject(json,User.class);
        System.out.println(user1);

    }
}


json-lib时间有些久远,jar包只更新到2010年

org.json用起来有些繁琐

Jackson、Gson、FastJson只需一两句话就可以搞定,更多关于fastJson的使用方式请点击这里


json入门内容参考来源:https://blog.csdn.net/n447194252/article/details/77747465

 

net.sf.json.JSONObject 和org.json.JSONObject 的差别:https://blog.csdn.net/qq_36688143/article/details/84135790

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值