what is JSON
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others.
These properties make JSON an ideal data-interchange language.
here is more detail: http://www.json.org/json-zh.html
经常用的JSON包有两种:json-lib 和 org-lib,这里直接介绍json-lib 两个都差不多。
官网:http://json-lib.sourceforge.net/
Json-lib requires (at least) the following dependencies in your classpath:
- jakarta commons-lang 2.5
- jakarta commons-beanutils 1.8.0
- jakarta commons-collections 3.2.1
- jakarta commons-logging 1.1.1
- ezmorph 1.0.6
依赖包可以在这里搜索下载:http://www.docjar.com/
最基本的方法:
都是JSONObject的静态方法
实例:
一个entity类:User.java
package com.hwadee.entity;
public class User {
private String name;
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
测试类:JsonTest.java
import java.util.ArrayList;
import java.util.List;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import com.hwadee.entity.User;
public class TestJson {
public static void main(String[] args) {
User user=new User();
user.setAge(1);
user.setName("test");
// String jsonStr="{'name':'test','age':'1'}";
//1:将单个对象转化为JSONString
JSONObject object=JSONObject.fromObject(user);
System.out.println(object.toString());
// 2:将集合转换为JSONString
// [{"age":2,"name":"test2"},{"age":3,"name":"test3"},{"age":4,"name":"test4"}]
List<User> users=new ArrayList<User>();
User u1=new User();
u1.setAge(2);
u1.setName("test2");
User u2=new User();
u2.setAge(3);
u2.setName("test3");
User u3=new User();
u3.setAge(4);
u3.setName("test4");
users.add(u1);
users.add(u2);
users.add(u3);
JSONArray jsonArray=JSONArray.fromObject(users);
System.out.println(jsonArray.toString());
//JsonStr To JsonArray
String jsons="[{'name':'test','age':'1'},{'name':'test4','age':'4'}]";
JSONArray array=JSONArray.fromObject(jsons);
for (int i = 0; i < array.size(); i++) {
JSONObject jo=(JSONObject) array.get(i);
System.out.println(jo.get("name"));
}
}
}