MyFastJson 个人笔记
程序员文章站
2024-03-18 18:46:52
...
转换用的实体 RiskSettings
public class RiskSettings implements Serializable{
/**
* 标识code
*/
private String code;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
Object < ---- >String
import java.util.List;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.shopuu.server.finance.risk.models.RiskSettings;
// Object -->String
RiskSettings javaObject=new RiskSettings();
javaObject.setCode("3223");
String string = JSONObject.toJSON(javaObject).toString();
System.out.println(string);//{"code":"3223"}
// String -->Object
RiskSettings parseObject = JSON.parseObject(string, RiskSettings.class);
String code = parseObject.getCode();
System.out.println(code);//3223
//String < ---- >JsonObject < ---- >Object
//String -->JsonObject -->Object
JSONObject jo = JSONObject.parseObject(string);
RiskSettings rs = JSONObject.toJavaObject(jo, RiskSettings.class);
System.out.println(rs.getCode());//3223
RiskSettings rs2 = JSON.toJavaObject(jo, RiskSettings.class);
System.out.println(rs2.getCode());//3223
//Object -->String --> JsonObject
String jsonString = JSON.toJSONString(rs);
JSONObject jo1 = JSONObject.parseObject(string);
// String 串封装成对象类型的json {"code":"3223"}
JSONObject jo = JSONObject.parseObject(string);
JSONObject content = new JSONObject();
content.put("riskSettings", jo);
System.out.println(content.toString());//{"riskSettings":{"code":"3223"}}
String < ---- >Map < ---- > Object
public <T> void strTmap(String string){
//String -->Map
Map<String, T> map = JSONObject.parseObject(string, Map.class);
System.out.println(map.get("code")); //3223
//Map -->String -->Object
String jsonString = JSONObject.toJSONString(map);
RiskSettings ts2 = JSON.parseObject(jsonString, RiskSettings.class);
System.out.println(ts2.getCode());//3223
}
//String --> list < Object >
//String --> list<Object>
String string="[{\"code\":\"3223\"},{\"code\":\"3223\"},{\"code\":\"3223\"}]";
List<String> l1 =JSON.parseArray(string, String.class);
List<RiskSettings> l2 =JSON.parseArray(string, RiskSettings.class);
List<Map<String,Object>> l3 =JSON.parseObject(string, new TypeReference<List<Map<String,Object>>>(){});
list<Object>也是一种 Object
本篇幅做的是最简单的转换,并没有添加过滤条件, 如果 后续项目需要再补充