一:org.json的使用

1.java生成json

1-1:通过JSONObject
    public static String createJson() {
        JSONObject toly = new JSONObject();

        toly.put("name", "toly");
        toly.put("age", 24);
        toly.put("birthday", "1994-03-28");
        toly.put("isman", false);
        toly.put("major", new String[]{"java", "c++"});

        return toly.toString();
    }
1-2:通过Map
    public static String createJsonByMap() {
        Map<String, Object> toly = new HashMap<String, Object>();

        toly.put("name", "toly");
        toly.put("age", 24);
        toly.put("birthday", "1994-03-28");
        toly.put("isman", false);
        toly.put("major", new String[]{"java", "c++"});

        return new JSONObject(toly).toString();
    }
1-3:通过bean
    public static String createJsonByBean() {
        Person toly = new Person();
        toly.setAge(24);
        toly.setName("toly");
        toly.setBirthday("1994-03-28");
        toly.setIsman(false);

        List<String> major = new ArrayList<String>();
        major.add("java");
        major.add("c++");
        toly.setMajor(major);
        return new JSONObject(toly).toString();
    }
生成的json格式化后:
{
    "age": 24,
    "birthday": "1994-03-28",
    "isman": false,
    "major": [
        "java",
        "c++"
    ],
    "name": "toly"
}

2.json解析

      public static Person parseJson(String json) {
        JSONObject object = new JSONObject(json);
        Person toly = new Person();
        if (!object.isNull("name")) {
            toly.setName(object.getString("name"));
        }
        if (!object.isNull("age")) {
            toly.setAge(object.getInt("age"));
        }
        if (!object.isNull("birthday")) {
            toly.setBirthday(object.getString("birthday"));
        }
        if (!object.isNull("isman")) {
            toly.setIsman(object.getBoolean("isman"));
        }
        if (!object.isNull("major")) {
            JSONArray major = object.getJSONArray("major");
            ArrayList<String> majors = new ArrayList<String>();
            for (int i = 0; i < major.length(); i++) {
                majors.add((String) major.get(i));
            }
            toly.setMajor(majors);
        }
        return toly;
    }
程序入口:json.Client#main
        File file = new File(Client.class.getResource("/toly.json").getFile());
        String s = FileUtils.readFileToString(file, "utf-8");
        Person toly = JsonParser.parseJson(s);
        System.out.println(toly);
F:\Intellij_idea\Java\json\src\main\java\toly.json
{
  "birthday": "1994-03-28",
  "major": [
    "java",
    "c++"
  ],
  "name": "toly",
  "isman": false,
  "age": 24
}
输出:
Person{name='toly', birthday='1994-03-28', age=24, isman=false, major=[java, c++]}

Gson的使用

1.生成json

    private static String createJsonByBeanUseGson() {
        Person toly = new Person();
        toly.setAge(24);
        toly.setName("toly");
        toly.setBirthday("1994-03-28");
        toly.setIsman(false);

        List<String> major = new ArrayList<String>();
        major.add("java");
        major.add("c++");
        toly.setMajor(major);
        return new Gson().toJson(toly);
    }
注:在bean对象的字段上加上 @SerializedName()注解,可自定义json键名,如:
    @SerializedName("DiaoSiName")
    private String name;
结果格式化后:
{
    "DiaoSiName": "toly",
    "age": 24,
    "birthday": "1994-03-28",
    "isman": false,
    "major": [
        "java",
        "c++"
    ]
}

2.json解析:

    private static void parseJsonUseGson() throws IOException {
        File file = new File(org_json.Client.class.getResource("/toly.json").getFile());
        String s = FileUtils.readFileToString(file, "utf-8");
        Gson gson = new Gson();
        Person person = gson.fromJson(s, Person.class);
        System.out.println(person);
    }

控制台:

Person{name='null', birthday='1994-03-28', age=24, isman=false, major=[java, c++]}

3.GsonBuilder自定义构造样式

    private static String createJsonByBeanUseGson() {
        Person toly = new Person();
        toly.setAge(24);
        toly.setName("toly");
        toly.setBirthday("1994-03-28");
        toly.setIsman(false);

        List<String> major = new ArrayList<String>();
        major.add("java");
        major.add("c++");
        toly.setMajor(major);

        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.setPrettyPrinting();//使得输出的json格式化
        gsonBuilder.setFieldNamingStrategy(new FieldNamingStrategy() {
            public String translateName(Field field) {
                if (field.getName().equals("name")) {
                    return "NAME";//更改字段名
                }
                return "z-"+field.getName();
            }
        });

        return gsonBuilder.create().toJson(toly);
    }
控制台:
{
  "NAME": "toly",
  "z-birthday": "1994-03-28",
  "z-age": 24,
  "z-isman": false,
  "z-major": [
    "java",
    "c++"
  ]
}
解析时的日期处理
    private static void parseJsonUseGsonFormateDate() throws IOException {
        File file = new File(org_json.Client.class.getResource("/toly.json").getFile());
        String s = FileUtils.readFileToString(file, "utf-8");
        Gson gson = new Gson();
        Person_Date person = gson.fromJson(s, Person_Date.class);
        System.out.println(person.getBirthday());
    }
控制台:
Mon Mar 28 00:00:00 CST 1994
posted on 2018-05-28 22:28  张风捷特烈  阅读(672)  评论(0编辑  收藏  举报