JSONBuilder的用法

一。JSONBuilder可以向文件中写入写入json字符串。如下面的例子:

 1 public class Test
 2 {
 3     public static void main(String args[]) throws IOException
 4     {
 5         File f = new File("d:" + File.separator + "test.txt");
 6         FileWriter fw = new FileWriter(f);
 7         JSONBuilder builder = new JSONBuilder(fw);
 8         builder.object();
 9         builder.key("Json");
10         builder.value("Hello, World!");
11         builder.endObject();
12         fw.flush();
13         fw.close();
14     }
15 }

二。JSONBuilder:可以把一个对象转成json的输出

GsonBuilder json=new GsonBuilder();

User user=new User();

user.setName("jjr");

String userJson=json.create().toJson(user);

 

三。可以写个工具类好调用

FastJsonUtil:
public class FastJsonUtil {
    public static String bean2Json(Object obj) {
        return JSON.toJSONString(obj);
    }
 
    public static <T> T json2Bean(String jsonStr, Class<T> objClass) {
        return JSON.parseObject(jsonStr, objClass);
    }
}

GsonUtil.java:

public class GsonUtil {
    private static Gson gson = new GsonBuilder().create();
 
    public static String bean2Json(Object obj) {
        return gson.toJson(obj);
    }
 
    public static <T> T json2Bean(String jsonStr, Class<T> objClass) {
        return gson.fromJson(jsonStr, objClass);
    }
 
    public static String jsonFormatter(String uglyJsonStr) {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        JsonParser jp = new JsonParser();
        JsonElement je = jp.parse(uglyJsonStr);
        return gson.toJson(je);
    }
}

JacksonUtil.java

public class JacksonUtil {
    private static ObjectMapper mapper = new ObjectMapper();
 
    public static String bean2Json(Object obj) {
        try {
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }
 
    public static <T> T json2Bean(String jsonStr, Class<T> objClass) {
        try {
            return mapper.readValue(jsonStr, objClass);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

JsonLibUtil.java

public class JsonLibUtil {
 
    public static String bean2Json(Object obj) {
        JSONObject jsonObject = JSONObject.fromObject(obj);
        return jsonObject.toString();
    }
 
    @SuppressWarnings("unchecked")
    public static <T> T json2Bean(String jsonStr, Class<T> objClass) {
        return (T) JSONObject.toBean(JSONObject.fromObject(jsonStr), objClass);
    }
}

 

 

posted @ 2019-10-18 15:27  heart..  阅读(1937)  评论(0编辑  收藏  举报