fastjson转换

public class JsonTest {
    @Test
    public void beanToString() {
        Animal animal = new Animal();
        animal.setName("娃哈哈");
        animal.setAge(12);

        String json = JSONObject.toJSONString(animal);
        System.out.println(json);
    }

    @Test
    public void stringToBean() {
        String json = "{\"age\":12,\"name\":\"娃哈哈\"}";

        Animal animal = JSONObject.parseObject(json, Animal.class);
        System.out.println(animal);
    }

    @Test
    public void stringToJSONObject() {
        String json = "{\"age\":12,\"name\":\"娃哈哈\"}";

        JSONObject jsonObject = JSONObject.parseObject(json);
        System.out.println(jsonObject);
    }

    @Test
    public void jsonObjectToString() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("age", 12);
        jsonObject.put("name", "娃哈哈");

        String str = jsonObject.toJSONString();
        System.out.println(str);
    }

    @Test
    public void jsonObjectToBean() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("age", 12);
        jsonObject.put("name", "娃哈哈");

        Animal animal = jsonObject.toJavaObject(Animal.class);
        System.out.println(animal);
    }

    @Test
    public void beanToJSONObject() {
        Animal animal = new Animal();
        animal.setName("娃哈哈");
        animal.setAge(12);

        JSONObject jsonObject = (JSONObject) JSONObject.toJSON(animal);
        System.out.println(jsonObject);
    }

    @Test
    public void stringToList() {
        String str = "[{\"age\":12,\"name\":\"娃哈哈\"},{\"age\":11,\"name\":\"啦啦啦\"}]";
        JSONArray jsonArray = JSONArray.parseArray(str);
        System.out.println(jsonArray);

        List<Animal> datas = JSONObject.parseArray(str, Animal.class);
        System.out.println(datas);
    }

    @Test
    public void listToJSON() {
        List<Animal> animals = Arrays.asList(
                new Animal("娃哈哈", 12),
                new Animal("啦啦啦", 11));

        JSONArray jsonArray = (JSONArray) JSONArray.toJSON(animals);
        System.out.println(jsonArray);

        String str = JSONArray.toJSONString(animals);
        System.out.println(str);
    }
}
发布了63 篇原创文章 · 获赞 8 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/myt0929/article/details/88403075