需要jar包
fastjson-1.2.73.jar
表
实体
package login;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
public class FastJson {
public static void main(String[] args) {
// string->json
// Role role = new Role(1,"只读");
**String json = JSON.toJSONString(role);
System.out.println(json)**;
//json-string
// String s = "{\"perm\":\"只读\",\"roleid\":1}";
// Role role = JSON.parseObject(s,Role.class);
// String qx = role.getPerm();
// System.out.println(qx);
以上与表有关
====================================================
单纯String<->json
// key->value 字符串转json
// String json = "{'abc':'1','hahah':'2'}";
// JSONObject jsonObject = JSONObject.parseObject(json);
// System.out.println(jsonObject);
// 取值
// String s1 = jsonObject.getString("abc");
// System.out.println(s1);
// 嵌套字符串转json
String message = "{'msg':'登录成功','code':0,'date':{'permissions':'0001'}}";
JSONObject jsonMap = JSON.parseObject(message);
System.out.println(jsonMap); // {"msg":"登录成功","date":{"permissions":"0001"},"code":0}
Object s2 = jsonMap.get("msg");
System.out.println(s2); //登录成功
Map s3 = JSON.parseObject(message).getJSONObject("date");
System.out.println(s3); //{"permissions":"0001"}
Object s4 = s3.get("permissions");
System.out.println(s4);// 0001
}
}