关于JSON的写法:
工具:检测文件里的Json是否写得正确
http://jsonlint.com/
常用的解析JSON的开源代码:
- GSON
- fastJSON
·······
GSON的用法:
-
使用GSON要先加上工具包,如图:
-
新建一个类UserData.java
public class UserData {
@SerializedName("title")
private String mTitle;
@SerializedName("content")
private String mContent;
@SerializedName("user")
private User mUser;
@SerializedName("images")
private List<String> mImages;public String getTitle() { return mTitle; } public void setTitle(String title) { mTitle = title; } public String getContent() { return mContent; } public void setContent(String content) { mContent = content; } public User getUser() { return mUser; } public void setUser(User user) { mUser = user; } public List<String> getImages() { return mImages; } public void setImages(List<String> images) { mImages = images; } public class User { @SerializedName("id") private long mID; @SerializedName("name") private String mName; @SerializedName("avatar") private String mAvatar; public long getID() { return mID; } public void setID(long ID) { mID = ID; } public String getName() { return mName; } public void setName(String name) { mName = name; } public String getAvatar() { return mAvatar; } public void setAvatar(String avatar) { mAvatar = avatar; } } }
注意事项:class里面的变量要和Json文本里面的key一致,
上面代码使用了@SerializedName(),可以将你自定义的变量名替换成Json的key
- 现在建完后可以解析JSON文档了
在需要的监听事件上写上
Gson gson = new Gson();
//jsonString是要解析的Json内容
UserData userData = gson.fromJson(jsonString, UserData.class);