首先下载json-lib-2.2.2-jdk15.rar,里面的jar包全部放到项目中。commons-beanutils-1.7.0.jar commons-collections-3.2.jar commons-lang-2.3.jar commons-logging-1.1.jar ezmorph-1.0.4.jar json-lib-2.2.2-jdk15.jar @H_404_3@
1.格式化bean@H_404_3@
User.java@H_404_3@
package com.json.bean; public class User { private int id; private String name; private int age; private String sex; public User(int id,String name,int age,String sex) { this.id = id; this.name = name; this.age = age; this.sex = sex; } //get set方法省略 } @H_404_3@
public static void main(String[] args) { User user = new User(100,"周星星",23,"男"); JSONObject jsonObject = JSONObject.fromObject(user); String json = jsonObject.toString(); System.out.println(json); } @H_404_3@
2.格式化map@H_404_3@
public static void main(String[] args) { Map<String,String> map = new HashMap<String,String>(); map.put("name","张三"); map.put("age","26"); map.put("sex","男"); JSONObject jsonObject = JSONObject.fromObject(map); String json = jsonObject.toString(); System.out.println(json); } @H_404_3@
3.格式化list@H_404_3@
public static void main(String[] args) { User u1 = new User(1,"张三","男"); User u2 = new User(2,"李四",24,"妖"); User u3 = new User(3,"王五",25,"女"); List<User> list = new ArrayList<User>(); list.add(u1); list.add(u2); list.add(u3); JSONArray jsonArray = JSONArray.fromObject(list); String json = jsonArray.toString(); System.out.println(json); } @H_404_3@ 原文链接:https://www.f2er.com/json/290788.html