1、不带包的使用方式
解压json和支持包在当前目录下生成
org
net
javac User.java
javac Test.java
java Test 输出
{"age":25,"name":"phl"}
[{"age":25,"name":"phl"},{"age":26,"name":"luckybird"}]
{"age":0,"name":""}
------------------User.java-----------------
public class User
{
private String name;
private int age;
public String getName()
{
return this.name;
}
public int getAge(){
return this.age;
}
public void setName(String v_name)
{
this.name=v_name;
}
public void setAge(int v_age)
{
this.age=v_age;
}
}
---------------Test.java------------------
import java.util.ArrayList;
import java.util.List;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
public class Test {
public static void main(String[] args) throws Exception {
User user = new User();
user.setName("phl");
user.setAge(25);
User user2 = new User();
user2.setName("luckybird");
user2.setAge(26);
List<User> list = new ArrayList<User>();
list.add(user);
list.add(user2);
JSONObject json = JSONObject.fromObject(user);
System.out.println(json.toString());
// ********************************************************
JSON json2 = JSONSerializer.toJSON(list);
System.out.println(json2.toString());
json2 = JSONSerializer.toJSON(new User());
System.out.println(json2.toString());
}
}
=====================================================================
2、带包的使用方式
------------------User.java-----------------
package nn;
public class User
{
private String name;
private int age;
public String getName()
{
return this.name;
}
public int getAge(){
return this.age;
}
public void setName(String v_name)
{
this.name=v_name;
}
public void setAge(int v_age)
{
this.age=v_age;
}
}
---------------Test.java------------------
package mm;
import java.util.ArrayList;
import java.util.List;
import net.sf.json.JSON;
import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import nn.User;
public class Test {
public static void main(String[] args) throws Exception {
User user = new User();
user.setName("phl");
user.setAge(25);
User user2 = new User();
user2.setName("luckybird");
user2.setAge(26);
List<User> list = new ArrayList<User>();
list.add(user);
list.add(user2);
JSONObject json = JSONObject.fromObject(user);
System.out.println(json.toString());
// ********************************************************
JSON json2 = JSONSerializer.toJSON(list);
System.out.println(json2.toString());
json2 = JSONSerializer.toJSON(new User());
System.out.println(json2.toString());
}
}
==================
javac User.java ->User.class
javac Test.java ->Test.class
拷贝User.class->nn目录下 ;Test.class->mm目录下
调用方式java mm.Test
{"age":25,"name":"phl"}
[{"age":25,"name":"phl"},{"age":26,"name":"luckybird"}]
{"age":0,"name":""}