基于json-lib.jar包Json实例程序
1.从头或者从零开始,创建一个JSONObject(Creating a JSONObject from
scratch)
实例1:
JSONObject jsonObject = new JSONObject();
jsonObject.element("name", "周星星");
jsonObject.element("sex",
"male");
jsonObject.element("age", 18);
jsonObject.element("job",
"student");
System.out.println(jsonObject.get("name"));// 周星星
System.out.println(jsonObject.get("job"));// student
System.out.println(jsonObject.getString("sex"));// male
System.out.println(jsonObject.getInt("age"));// 18
实例2:
JSONObject
jsonObject = new JSONObject().element("string", "JSON").element("integer",
"1").element("double", "2.0").element("boolean", "true");
assertEquals("JSON", jsonObject.getString("string"));
assertEquals(1,
jsonObject.getInt("integer"));
assertEquals(2.0d,
jsonObject.getDouble("double"), 0d);
assertTrue(jsonObject.getBoolean("boolean"));
注:这是对实例1的一个简化版
2.使用一个JSON格式化字符串来创建一个JSONObject(Creating a JSONObject from a JSON
formatted string)
实例1:
String json =
"{name:/"周星星/",sex:/"male/",age:18,job:/"student/"}";
JSONObject
jsonObject = JSONObject.fromObject(json);
//或者使用 JSONObject jsonObject =
(JSONObject) JSONSerializer.toJSON(json);
System.out.println(jsonObject.get("name"));// 周星星
System.out.println(jsonObject.get("job"));// student
System.out.println(jsonObject.getString("sex"));// male
System.out.println(jsonObject.getInt("age"));// 18
实例2:
String str =
"{'string':'JSON', 'integer': 1, 'double': 2.0, 'boolean': true}";
JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON(str);
assertEquals("JSON", jsonObject.getString("string"));
assertEquals(1,
jsonObject.getInt("integer"));
assertEquals(2.0d,
jsonObject.getDouble("double"), 0d);
assertTrue(jsonObject.getBoolean("boolean"));
3.使用一个Map来创建一个JSONObject(Creating a JSONObject from a
Map)
实例1:
Map map = new HashMap();
map.put( "string",
"JSON" );
map.put( "integer", "1" );
map.put( "double", "2.0"
);
map.put( "boolean", "true" );
JSONObject jsonObject =
(JSONObject) JSONSerializer.toJSON( map );
assertEquals( "JSON",
jsonObject.getString("string") );
assertEquals( 1,
jsonObject.getInt("integer") );
assertEquals( 2.0d,
jsonObject.getDouble("double"), 0d );
assertTrue(
jsonObject.getBoolean("boolean") );
4.使用一个JavaBean来创建一个JSONObject(Creating a JSONObject from a
JavaBean)
实例1:
public class Mybean {
private String
string;
private int integer;
private double dooble;
private
boolean bool;
// getters &
setters
}
Mybean bean = new
Mybean();
bean.setString("JSON");
bean.setInteger(1);
bean.setDooble(2.0d);
bean.setBool(true);
JSONObject
jsonObject = (JSONObject) JSONSerializer.toJSON(bean);
assertEquals("JSON",
jsonObject.getString("string"));
assertEquals(1,
jsonObject.getInt("integer"));
assertEquals(2.0d,
jsonObject.getDouble("dooble"),
0d);
assertTrue(jsonObject.getBoolean("bool"));
由此可见,无论要转换的源是哪种类型,都可以使用(JSONObject)
JSONSerializer.toJSON()或JSONObject.fromObject()来转换;