java中json数据生成和解析(复杂对象演示)

1.json简单介绍

  1.1 json是最流行和广泛通用的数据传输格式,简称JavaScript Object Notation,最早在JavaScript中使用.

  1.2 举个例子,下面是一个json对象,名字叫王尼玛,他有两个粉丝组成数组,一个叫小王,一个叫小尼玛:

   

{
      "name":"王尼玛",
      "fans":[{
            "name":"小王",
            "age":"7"
           },{
            "name":"小尼玛",
            "age":"10"
           }]
      }

2.json数据生成和解析

  2.1 关于json处理的包有好几类,开源jackson,谷歌Gson,阿里巴巴的Fastjson.Gson功能强大,但是Fastjson性能更快.如何选择见仁见智就行

  2.2 这里我开始都是用org.json,后面为了演示复杂json转java bean又导入了功能强大的Gjson,先附上两个maven依赖:

<!-- https://mvnrepository.com/artifact/org.json/json -->
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20160810</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.7</version>
        </dependency>

  2.3 json数据的生成,也就是各种类型转json.(String,map和java bean)

DemoCreateJson.java

import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by garfield on 2016/10/16.
 * 举三种创建json的例子
 */
public class DemoCreateJson {
    public static void main(String[] args) {
        StringCreateJson();
        mapCreateJson();
        beanCreateJson();
    }
    //String创建json
    /**
     * {
           "name":"王尼玛",
           "fans":[{
                 "name":"小王",
                 "age":"7"
                },{
                 "name":"小尼玛",
                 "age":"10"
                }]
           }
     */
    static void StringCreateJson(){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("name","王尼玛");

        //粉丝是个数组,其实就是嵌套json
        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("name","小王");
        jsonObject1.put("age",7);

        JSONObject jsonObject2 = new JSONObject();
        jsonObject2.put("name","小尼玛");
        jsonObject2.put("age",10);

        //从此处可以看出其实list和json也是互相转换的
        List<JSONObject> jsonObjects = new ArrayList<JSONObject>();
        jsonObjects.add(jsonObject1);
        jsonObjects.add(jsonObject2);
        jsonObject.put("fans",jsonObjects);

        System.out.println("jsonObject直接创建json:" + jsonObject);
    }
    //第二种方法,用map方式
    static void mapCreateJson(){
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("name","王尼玛");
        Map<String,Object> map1 = new HashMap<String,Object>();
        map1.put("name","小王");
        map1.put("age",7);
        Map<String,Object> map2 = new HashMap<String,Object>();
        map2.put("name","小尼玛");
        map2.put("age",10);
        List<Map> jsonObjects = new ArrayList<Map>();
        jsonObjects.add(map1);
        jsonObjects.add(map2);
        map.put("fans",jsonObjects);
        System.out.println("集合中Map创建json对象:" + new JSONObject(map));
    }
    //第三种,也是比较常用的,用bean转换,(这里用的是map作为子json,如果必须要创建复杂bean对象,建议用Gjson操作)
    static void beanCreateJson(){
        Actor actor = new Actor();
        actor.setName("王尼玛");
        Map<String,Object> map1 = new HashMap<String,Object>();
        map1.put("name","小王");
        map1.put("age",7);
        Map<String,Object> map2 = new HashMap<String,Object>();
        map2.put("name","小尼玛");
        map2.put("age",10);
        List<Map> maps = new ArrayList<Map>();
        maps.add(map1);
        maps.add(map2);
        actor.setFans(maps);
        System.out.println("java bean创建json对象:" + new JSONObject(actor));
    }
第四种 我在项目中使用的一种,使用将对象利用GSON解析成json字符串,也是项目中传递的json数据的常见应用
该json数据为{"deviceKey":"00004G4A","function":{"ic_card":"hajksd44/,sj"}}
private  void testJson(){
    ICJson icJson=new ICJson("00004G4A",new Function("hajksd44/,sj"));
    Gson gson=new Gson();
    gson.toJson(icJson);
    Log.d("zzzzzaa", gson.toJson(icJson));}}

2.3.0 ICJson与Function类

public class Function {
        private String ic_card;

    public Function(String ic_card) {
        this.ic_card = ic_card;
    }

        public String getIc_card() {
            return ic_card;
        }

        public void setIc_card(String ic_card) {
            this.ic_card = ic_card;
        }

    @Override
    public String toString() {
        return "Function{" +
                "ic_card='" + ic_card + '\'' +
                '}';
    }
}
public class ICJson {
    private String deviceKey;
    private Function function;

    public ICJson(String deviceKey, Function function) {
        this.deviceKey = deviceKey;
        this.function = function;
    }

    public String getDeviceKey() {
        return deviceKey;
    }

    public void setDeviceKey(String deviceKey) {
        this.deviceKey = deviceKey;
    }

    public Function getFunction() {
        return function;
    }

    public void setFunction(Function function) {
        this.function = function;
    }

    @Override
    public String toString() {
        return "ICJson{" +
                "deviceKey='" + deviceKey + '\'' +
                ", function=" + function +
                '}';
    }
}

2.3.1上面类缺少基本bean

Actor.java

import java.util.List;
import java.util.Map;

/**
 * Created by garfield on 2016/10/16.
 */
public class Actor {
    private String name;
    private List<Map> fans;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Map> getFans() {
        return fans;
    }

    public void setFans(List<Map> fans) {
        this.fans = fans;
    }

}

  2.4 json的解析,这里写了两种解析方式,同样,比较常用的还是第二种,json转java bean

DemoParseJson.java

import com.google.gson.*;
import org.json.JSONObject;

import java.util.Map;

/**
 * Created by garfield on 2016/10/16.
 */
public class DemoParseJson {
    public static void main(String[] args) {
        String jsonString = "{\"fans\":[{\"name\":\"小王\",\"age\":7},{\"name\":\"小尼玛\",\"age\":10}],\"name\":\"王尼玛\"}";
        normalParse(jsonString);
        beanParse(jsonString);
    }
    static void normalParse(String jsonString){
        JSONObject jsonObject = new JSONObject(jsonString);
        //获取普通属性
        System.out.println("姓名:");
        System.out.println("  " + jsonObject.getString("name"));
        //获取数组
        System.out.println("粉丝:");
        for (Object fan : jsonObject.getJSONArray("fans")) {
            JSONObject object = (JSONObject)fan;
            System.out.println("  姓名:" + object.get("name") + ",年龄:" + object.get("age"));
        }
    }
    //org.json并不支持这种复杂的bean转换,所以这边又导入了gson的包
    static void beanParse(String jsonString){
        System.out.println("=========Gson解析=========");
        JsonObject obj = new JsonParser().parse(jsonString).getAsJsonObject();
        Actor actor = new Gson().fromJson(obj,Actor.class);
        System.out.println("姓名:");
        System.out.println("  " + obj.get("name"));
        System.out.println("粉丝:");
        for (Map map : actor.getFans()) {
            System.out.println("  姓名:" + map.get("name") + "年龄:" + map.get("age"));
        }
    }
}

  2.4.1顺便附上执行结果:

姓名:
  王尼玛
粉丝:
  姓名:小王,年龄:7
  姓名:小尼玛,年龄:10
=========Gson解析=========
姓名:
  "王尼玛"
粉丝:
  姓名:小王年龄7.0
  姓名:小尼玛年龄10.0