以下使用的都是fastJson。
先創建Person類,如下:
public class Person {
@JSONField(name = "AGE")
private int age;
@JSONField(name = "FULL NAME")
private String fullName;
@JSONField(name = "DATE OF BIRTH",format="yyyy-MM-dd hh:mm:ss")
private Date dateOfBirth;
public Person(int age, String fullName, Date dateOfBirth) {
super();
this.age = age;
this.fullName= fullName;
this.dateOfBirth = dateOfBirth;
}
// 標准 getters & setters
}
Java 對象轉換為 JSON字符串
JSON.toJSONString() 將 Java 對象(或集合)轉換換為 JSON字符串。
假設person為Java對象,則如下:
String jsonStr= JSON.toJSONString( person);
JSON 字符串轉換成Java對象。
parseObject 方法可以將 JSON 字符串轉換成Java對象。
假設JSON字符串為jsonStr,如下:
Person newPerson = JSON.parseObject( jsonStr, Person.class);
JSON 字符串轉換成JSONObject對象
JSONObject paramJson= JSON.parseObject(jsonStr);
JSONObject對象json轉換成JSON 字符串
JSONObject json = new JSONObject();
json.toString();
JSONObject移除元素
可以用remove()方法移除JSONObject的某個鍵值。
public static void main(String[] args) {
String str="{\"buyerTaxNo\": \"440301999999980\",\"errorIds\": \"123\"}";
JSONObject jsonObject= JSON.parseObject(str);
jsonObject.remove("errorIds");
System.out.println(jsonObject);
}
JSONArray
JSONArray轉化為List
Json格式如下:
{
"clientList": [ "DYeGPUueoRGf1zVuFS2w","rcuGVmcWD9apAL2lwIAt" ]
}
解析代碼如下:
String clientIdJson=orderJson.getString("clientList");
List<String> clientIdList= JSONArray.parseArray(clientIdJson,String.class);
遍歷JSONArray
for(int i=0;i<jsonArray.size();i++){
JSONObject jsonobject=jsonArray.getJSONObject(i);
}
待補充。