fastjson SupportArrayToBean 出错

bakd9h0s  于 2022-12-31  发布在  其他
关注(0)|答案(1)|浏览(134)
public class TestLast {
	static class Model {
		public int id;
		public String name;
	}

	public static void main(String[] args) {
		Model model = new Model();
		model.id = 1001;
		model.name = "gaotie";

		// {"id":1001,"name":"gaotie"}
		String text_normal = JSON.toJSONString(model);
		System.out.println(text_normal);

		// [1001,"gaotie"]
		String text_beanToArray = JSON.toJSONString(model,
				SerializerFeature.BeanToArray);
		System.out.println(text_beanToArray);

		// support beanToArray & normal mode
		System.out.println(JSON.parseObject(text_beanToArray,
				Feature.SupportArrayToBean));
	}
}

报错:
{"id":1001,"name":"gaotie"}
[1001,"gaotie"]
Exception in thread "main" java.lang.ClassCastException: com.alibaba.fastjson.JSONArray cannot be cast to com.alibaba.fastjson.JSONObject
at com.alibaba.fastjson.JSON.parseObject(JSON.java:208)
at fastJsonTest.TestLast.main(TestLast.java:28)

fastjson版本 1.2.28
jdk版本 :1.8

yyhrrdl8

yyhrrdl81#

测试代码写错了,漏传入Model.class啦

System.out.println(JSON.parseObject(text_beanToArray, Model.class, Feature.SupportArrayToBean));

相关问题