fastjson序列化,默認是用字母排序,
那么怎么來實現按照自己定義的順序輸出,想要的json串呢?
直接上代碼:
import com.alibaba.fastjson.annotation.JSONType; //設置排序規則 @JSONType(orders = { "busiCode", "message"}) public class TransMessage { String busiCode; Message message; public String getBusiCode() { return busiCode; } public void setBusiCode(String busiCode) { this.busiCode = busiCode; } public Message getMessage() { return message; } public void setMessage(Message message) { this.message = message; } }
@JSONType與Serializable同時存在,jsontype的orders屬性不起作用 to @JSONType中order未指明的字段,必須用@JSONField(serialize=false)修飾,否則排序無效
測試代碼如下:
@Test public void getBody(){ List skill = new ArrayList(); skill.add("Java"); skill.add("IOS"); skill.add("Android"); User user = new User(); user.setName("SOJSON"); user.setAge(27); user.setSex("男"); user.setSkill(skill); String json = JSON.toJSONString(user); System.out.println(json); }
運行結果如下:
{"name":"SOJSON","age":27,"sex":"男","skill":["Java","IOS","Android"]}
