- 0
- 0
- 约1.97千字
- 约 2页
- 2023-05-12 发布于湖北
- 举报
一、将任意的 javaBean 对象转换为 json 字符串:
Object obj=XXX;//任意一个 javabean 的对象都可以,但是这个javaBean 必须是公开的,否则会报找不到 get 方法。
JSONObject jo=JSONObject.fromObject(obj); System.out.println(jo.toString());
类似。
如果你的 obj 知道具体类型的话,还[可以使用 JSONArray 等对象来转换。其方法也
二、将 json 字符串转换为 javaBean 对象: String str=json 字符串对象;
JSONObject jo=JSONObject.fromObject(obj); T t=(T)JSONObject.toBean(jo,T.class);
XXXX
实例:
简单的测试代码:
import java.util.List;
import net.sf.json.JSONObject; public class Test {
public static void main(String[] args) throws Exception { JSONObject jo = JSONObject.fromObject(new T()); String str = (jo.toString());
System.out.println(str);
JSONObject jo2 = JSONObject.fromObject(str); T t = (T) JSONObject.toBean(jo2, T.class); ListT2 lists2 = (t.getTest2());
for (Object t2 : lists2) {//这里的 Object 如果直接写成T2 的话,会出错的,原因是JSON 转换后的 lists2 对象因为它不知道类型,就解析成 JSON 里的某种格式了,我们需要再调用相同的方法将其转成我们所知的 JavaBean
System.out.println(((T3) JSONObject.toBean(JSONObject.fromObject(t2), T3.class)).getAaa());
}
ListString l3 = t.getListString(); for (String s : l3) {
System.out.println(s);
}
}
}
运行结果:
{test2:[{aaa:testAAA,bbb:testBBB},{aaa:testAAA,bbb:testBBB},{aaa:testAAA, bbb:testBBB},
{aaa:testAAA,bbb:testBBB},{aaa:testAAA,bbb:testBBB}],age:15,listString:[ 中华人民共和国,
中华人民共和国,中华人民共和国],str:testStr} testAAA
2010-5-1 0:41:50 net.sf.json.JSONObject toBean
警告: Tried to assign property bbb:java.lang.String to bean of class T3 2010-5-1 0:41:50 net.sf.json.JSONObject toBean
警告: Tried to assign property bbb:java.lang.String to bean of class T3 testAAA
2010-5-1 0:41:50 net.sf.json.JSONObject toBean
警告: Tried to assign property bbb:java.lang.String to bean of class T3 testAAA
2010-5-1 0:41:50 net.sf.json.JSONObject toBean
警告: Tried to assign property bbb:java.lang.String to bean of class T3 testAAA
2010-5-1 0:41:50 net.sf.json.JSONObject toBean
警告: Tried to assign property bbb:java.lang.String to bean of class T3 testAAA
中华人民共和国中华人民共和国中华人民共和国
您可能关注的文档
- If引导的两种从句.docx
- if引导的条件状语从句58918.docx
- IIR切比雪夫低通数字滤波器.docx
- IMA分析和总结分析和总结.docx
- IMS题库分析和总结.docx
- INFINEON DAVE4使用教程分析和总结.docx
- intermediateaccounting 练习题 分析和总结.docx
- Internet与网络基础分析和总结.docx
- inter词根的意思分析和总结.docx
- InTouch通过以太网连接施耐德昆腾PLC10P.docx
- 2025年全国演出经纪人员资格认定考试试卷带答案(研优卷).docx
- 2025年全国演出经纪人员资格认定考试试卷完整版.docx
- 2025年全国演出经纪人员资格认定考试试题库及完整答案.docx
- 2025年全国演出经纪人员资格认定考试试卷完美版.docx
- 2025年全国演出经纪人员资格认定考试试卷含答案(实用).docx
- 2025年全国演出经纪人员资格认定考试试卷及答案(各地真题).docx
- 2025年下半年内江市部分事业单位公开考试招聘工作人员(240人)备考题库附答案.docx
- 2025年全国演出经纪人员资格认定考试试卷及答案1套.docx
- 2025年下半年四川成都市郫都区面向社会引进公共类事业单位人员2人备考题库最新.docx
- 2025年下半年内江市部分事业单位公开考试招聘工作人员(240人)备考题库附答案.docx
原创力文档

文档评论(0)