java分析以下代码被给出建议和修改后的代码public class JsonUserTest1 public static void mainString args user user = new user1001 韦汉臣 18 南宁 new Date; String s = JSONtoJSONStringuser;
建议和修改后的代码如下:
import java.util.Date;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
public class JsonUserTest1 {
public static void main(String[] args) {
User user = new User(1001, "韦汉臣", 18, "南宁", new Date());
String s = JSON.toJSONString(user);
System.out.println(s);
JSONObject o = JSON.parseObject(s);
System.out.println(o);
System.out.println(o.getInteger("id"));
System.out.println(o.getString("name"));
System.out.println(o.getInteger("age"));
System.out.println(o.getString("address"));
System.out.println(o.getDate("birth"));
}
}
修改说明:
- 类名应该首字母大写,修改
user为User。 - 导入
com.alibaba.fastjson.JSON和com.alibaba.fastjson.JSONObject。 - 使用
JSON.parseObject()方法将JSON字符串解析为JSONObject对象。 - 使用
getXXX()方法获取JSONObject中的字段值,其中XXX表示字段类型,如getInteger()、getString()、getDate()等
原文地址: http://www.cveoy.top/t/topic/is8r 著作权归作者所有。请勿转载和采集!