日期:2014-05-16 浏览次数:20474 次
package test; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; public class Test { public static void main(String[] args) throws JsonGenerationException, JsonMappingException, IOException { ObjectMapper mapper = new ObjectMapper(); 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); System.out.println(mapper.writeValueAsString(list)); } }
package test; 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()); } }