三种json类库举例

三种类库为:json-lib;Gson;Jackson

用法源码见附件。

1:json-lib

 中心jar:json-lib-2.4.jar

 支持jar:

 commons-beanutils-1.9.2.jar

 commons-collections-3.2.1.jar

 commons-lang-2.6.jar

 commons-logging-1.1.3.jar

 ezmorph-1.0.6.jar

 用法举例:

 // 创建JSONObject对象

private static JSONObject createJSONObject() {

JSONObject jsonObject = new JSONObject();

jsonObject.put("name", "kevin");

jsonObject.put("age", 20);

jsonObject.put("sex", "男");

return jsonObject;

}


public static void main(String[] args) {

JSONObject jsonObject = createJSONObject();

// 添加属性

jsonObject.element("job", "程序员");

// 获取属性值

System.out.println(jsonObject.get("job"));


// jsonObject转String

String jsonString = jsonObject.toString();

System.out.println(jsonString);

//String转jsonObject

JSONObject jsonObject2 = jsonObject.fromObject(jsonString);

System.out.println(jsonObject2.get("name"));

}

2:Gson

  需要的jar:gson-2.2.4.jar

  public static User createUser(){

User u = new User();

u.setAge(20);

u.setJob("程序员");

u.setName("lyl");

u.setSex("男");

return u;

}

public static void main(String[] args) {

User u = createUser();

Gson gson = new Gson();

//对象转json串

String gsonString = gson.toJson(u);

System.out.println(gsonString);

//json串转对象

User u2 = gson.fromJson(gsonString, User.class);

System.out.println(u2.getName());

}


3:jackson

 中心jar:jackson-core-2.3.2.jar

 其他支持jar

 jackson-annotations-2.3.2.jar

 jackson-databind-2.3.2.jar

  public static User createUser(){

User u = new User();

u.setAge(20);

u.setJob("程序员");

u.setName("lyl");

u.setSex("男");

return u;

}

public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {

ObjectMapper mapper = new ObjectMapper();

User u = createUser();

//json对象转json串

Writer strWriter = new StringWriter();

mapper.writeValue(strWriter, u);

String userDataJSON = strWriter.toString();

System.out.println(userDataJSON);

//json串转json对象

User userFromJSON = mapper.readValue(userDataJSON, User.class);

System.out.println(userFromJSON);

}


你可能感兴趣的:(json,gson,jar)