1、使用javaBean 构建json,代码演示如下:
package com.xie;
import java.util.HashMap;
import java.util.Map;
import javax.swing.plaf.synth.SynthSpinnerUI;
import com.alibaba.fastjson.*;
import com.alibaba.fastjson.JSONObject;
import org.json.*;
public class JsonTest {
private String name ;
private int age;
private Boolean sex;
public String getName() {return name;}
public void setName(String name) {this.name = name;}
public int getAge() {return age;}
public void setAge(int age) {this.age = age;}
public Boolean getSex() {return sex;}
public void setSex(Boolean sex) {this.sex = sex;}
public static void main(String arg[]){
JsonTest jsonTest = new JsonTest();
jsonTest.setName("张三");
jsonTest.setAge(20);
jsonTest.setSex(true);
String jsonString = creatJsonByBean(jsonTest);
System.out.println(jsonString);
}
public static String creatJsonByBean(JsonTest jsonTest){
org.json.JSONObject obj = new org.json.JSONObject(jsonTest);
System.out.println(obj.toString());
return obj.toString();
}
}
2、使用HashMap穿件json,演示代码如下:
package com.xie;
import java.util.HashMap;
import java.util.Map;
import javax.swing.plaf.synth.SynthSpinnerUI;
import com.alibaba.fastjson.*;
import com.alibaba.fastjson.JSONObject;
import org.json.*;
public class JsonTest {
public static void main(String arg[]){
String jsonString = creatJsonByHashMap();
System.out.println(jsonString);
}
public static String creatJsonByHashMap(){
Map map = new HashMap();
map.put("name", null);
map.put("age", 18);
map.put("sex", false);
JSONObject obj = new JSONObject(map);
return obj.toString();
}
}
3、一般创建json
public static String creatJson(){
JSONObject obj = new JSONObject();
obj.put("name","王五");
obj.put("age", 19);
obj.put("sex", true);
System.out.println(obj.toString());
return obj.toString();
}