Java JSON

丌官利
2023-12-01

本文内容来自JSON快速入门(Java版)

Java JSON

JSON是一种与开发语言无关的、轻量级的数据格式。全称JavaScript Object Notation.

优点:易于人的阅读和编写,易于程序解析与生产

数据结构

  • Object 使用花括号{}包含的键值对结构,Key必须是string类型(必须用双引号),value为任何基本类型或数据结构
  • Array 使用中括号[]来起始,并用逗号,来分隔元素

基本类型

  • string
  • number
  • true
  • false
  • null

注意:在JSON中没有时间或日期这样的类型,也没有注释

JSON IN Java

本例子使用的是stleary/JSON-java,文档位置是http://stleary.github.io/JSON-java/index.html

Maven地址org.json

如下简单的例子,创建一个JSONObject,可能会抛出异常JSONException

private static void JSONObject() {

    JSONObject object = new JSONObject();
    Object nullObj = null;
    try {
        object.put("name", "王小二");
        object.put("age", 25.2);
        object.put("birthday", "1990-01-01");
        object.put("school", "蓝翔");
        object.put("major", new String[] {"理发", "挖掘机"});
        object.put("has_girlfriend", false);
        object.put("car", nullObj);
        object.put("house", nullObj);
        object.put("comment", "这是一个注释");

        System.out.println(object.toString());

    } catch (JSONException e) {
        e.printStackTrace();
    }

}

控制台输出结果为:{"birthday":"1990-01-01","major":["理发","挖掘机"],"school":"蓝翔","name":"王小二","has_girlfriend":false,"comment":"这是一个注释","age":25.2}

使用Map构架JSON

使用HashMap构建JSON

private static void createJsonByMap(){
    Object nullObj = null;
    Map<String, Object> object = new HashMap<String, Object>();
    object.put("name", "王小二");
    object.put("age", 25.2);
    object.put("birthday", "1990-01-01");
    object.put("school", "蓝翔");
    object.put("major", new String[] {"理发", "挖掘机"});
    object.put("has_girlfriend", false);
    object.put("car", nullObj);
    object.put("house", nullObj);
    object.put("comment", "这是一个注释");

    System.out.println(new JSONObject(object));

}

使用Java Bean构建对象

例如,创建DiaoSi

public class DiaoSi {

    private String name;
    private String school;
    private boolean has_girlfriend;
    private double age;
    private Object car;
    private Object house;
    private String[] major;
    private String comment;
    private String birthday;

    //getter setter
}

通过bean创建JSON对象:

public static void createJsonByBean() {

    DiaoSi bean = new DiaoSi();
    bean.setName("王小二");
    bean.setAge(25.2);
    bean.setBirthday("1990-01-01");
    bean.setSchool("蓝翔");
    bean.setMajor(new String[] {"理发", "挖掘机"});
    bean.setHas_girlfriend(false);
    bean.setHouse(null);
    bean.setCar(null);
    bean.setComment("这是一个注释");
    System.out.println(new JSONObject(bean));

}

从文件中读取JSON

这里用到了common io

从文件中读取json,并输出

    File file = new File(ReadJSONSample.class.getResource("/wangxiaoer.json").getFile());
    String content = FileUtils.readFileToString(file);
    JSONObject jsonObject = new JSONObject(content);
    System.out.println("name : " + jsonObject.getString("name"));
    System.out.println("age : " + jsonObject.getDouble("age"));
    System.out.println("has_girlfriend : " + jsonObject.getBoolean("has_girlfriend"));
    System.out.println("major : " + jsonObject.getJSONArray("major"));

对于Array,可以使用如下的方式:

    JSONArray majorArray =  jsonObject.getJSONArray("major");
    for(int i=0; i < majorArray.length(); i++){
        String m = (String) majorArray.get(i);
        System.out.println("major-" + i + m);
    }

使用isNull来判断是否为null

    if (!jsonObject.isNull("name")) {
        System.out.println("name : " + jsonObject.getString("name"));
    }

GSON

google/gson

GSON生成JSON数据

通过bean来创建JSON

    DiaoSi bean = new DiaoSi();
    bean.setName("王小二");
    bean.setAge(25.2);
    bean.setBirthday("1990-01-01");
    bean.setSchool("蓝翔");
    bean.setMajor(new String[] {"理发", "挖掘机"});
    bean.setHas_girlfriend(false);
    bean.setHouse(null);
    bean.setCar(null);
    bean.setComment("这是一个注释");

    Gson gson = new Gson();
    System.out.println(gson.toJson(bean));

输出结果为:{"name":"王小二","school":"蓝翔","has_girlfriend":false,"age":25.2,"major":["理发","挖掘机"],"comment":"这是一个注释","birthday":"1990-01-01"}

使用@SerializedName改变生成JSON的key的值,例如

@SerializedName("NAME")
private String name;

则生成JSON的结果为:{"NAME":"王小二","school":"蓝翔","has_girlfriend":false,"age":25.2,"major":["理发","挖掘机"],"comment":"这是一个注释","birthday":"1990-01-01"}

GsonBuilder在JSON构建过程中做自定义

如下美化JSON:

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.setPrettyPrinting();
    Gson gson = gsonBuilder.create();
    System.out.println(gson.toJson(bean));

输出结果为:

{
  "NAME": "王小二",
  "school": "蓝翔",
  "has_girlfriend": false,
  "age": 25.2,
  "major": [
    "理发",
    "挖掘机"
  ],
  "comment": "这是一个注释",
  "birthday": "1990-01-01"
}

如下,使用setFieldNamingStrategyage变成大写

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.setPrettyPrinting();
    gsonBuilder.setFieldNamingStrategy(new FieldNamingStrategy() {

        public String translateName(Field f) {
            if (f.getName().equals("age")) {
                return "AGE";
            }
            return f.getName();
        }
    });
    Gson gson = gsonBuilder.create();
    System.out.println(gson.toJson(bean));

输出结果为:

{
  "NAME": "王小二",
  "school": "蓝翔",
  "has_girlfriend": false,
  "AGE": 25.2,
  "major": [
    "理发",
    "挖掘机"
  ],
  "comment": "这是一个注释",
  "birthday": "1990-01-01"
}

如果有些属性不想暴露,可以使用transient,表示在JSON生成过程中忽略掉该属性

private transient String ignore;

GSON解析

从文件中读取json,并转换为一个bean

    File file = new File(ReadJSONSample.class.getResource("/wangxiaoer.json").getFile());
    String content = FileUtils.readFileToString(file);
    Gson gson = new Gson();
    DiaoSi bean = gson.fromJson(content, DiaoSi.class);
    System.out.println(bean);

日期转换

    File file = new File(ReadJSONSample.class.getResource("/wangxiaoer.json").getFile());
    String content = FileUtils.readFileToString(file);
    Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
    DiaoSiWithBirthday bean = gson.fromJson(content, DiaoSiWithBirthday.class);
    System.out.println(bean);

输出结果:DiaoSi [name=王小二, school=蓝翔, has_girlfriend=false, age=25.2, car=null, house=null, major=[理发, 挖掘机], comment=这是一个注释, birthday=Mon Jan 01 00:00:00 CST 1990]

集合类型解析

json数组转为对象数组
参考GSON turn an array of data objects into json - Android

import com.google.gson.Gson;
import java.util.List;
import java.util.ArrayList;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;


public class Test {

  public static void main (String[] args) {

    // Initialize a list of type DataObject
    List<DataObject> objList = new ArrayList<DataObject>();
    objList.add(new DataObject(0, "zero"));
    objList.add(new DataObject(1, "one"));
    objList.add(new DataObject(2, "two"));

    // Convert the object to a JSON string
    String json = new Gson().toJson(objList);
    System.out.println(json);

    // Now convert the JSON string back to your java object
    Type type = new TypeToken<List<DataObject>>(){}.getType();
    List<DataObject> inpList = new Gson().fromJson(json, type);
    for (int i=0;i<inpList.size();i++) {
      DataObject x = inpList.get(i);
      System.out.println(x);
    }

  }


  private static class DataObject {
    private int a;
    private String b;

    public DataObject(int a, String b) {
      this.a = a;
      this.b = b;
    }

    public String toString() {
      return "a = " +a+ ", b = " +b;
    }
  }

}

总结

JSON是Android SDK官方的库
GSON适用于服务端开服,GSON比JSON功能更强大。

参考

 类似资料:

相关阅读

相关文章

相关问答