0
樣品JSON數據試圖手動JSON轉換爲類對象過程中自動
{
"Status": true,
"Message": "Roles retrieved successfully",
"Data": [
{
"Role": "SuperAdmin",
},
{
"Role": "Admin",
}
]
}
角色類
public class Role {
public int Role;
public int getRole() {
return Role;
}
public void setRoleID(String role) {
Role = role;
}
}
JSON數據等價類
public class RoleData {
public String Message;
public boolean Status;
public List<Role> Data;
public String getMessage() {
return Message;
}
public void setMessage(String message) {
Message = message;
}
public boolean isStatus() {
return Status;
}
public void setStatus(boolean status) {
Status = status;
}
public List<Role> getData() {
return Data;
}
public void setData(List<Role> data) {
Data = data;
}
}
下面是我的代碼來解析檢索的JSON數據導入型RoleData的類對象
private void parseJsonResponse(String responsestring) throws JSONException {
RoleData roleData = new RoleData();
JSONObject response = new JSONObject(responsestring);
if ((response == null) || response.length() == 0) {
return;
}
try {
if (response.getBoolean("Status")) {
JSONArray data = response.getJSONArray("Data");
List<Role> temp = new ArrayList<Role>();
for (int i = 0; i < data.length(); i++) {
JSONObject dataObj = data.getJSONObject(i);
Role role = new Role();
role.setRole(dataObj.getString("Role"));
roleData.setMessage(response.getString("Message"));
roleData.setStatus(response.getBoolean("Status"));
temp.add(role);
}
roleData.setData(temp);
}
}catch(JSONException e){
e.printStackTrace();
}
}
問題
有沒有更好的辦法來避免上面寫着解析代碼?在.NET中,我們可以使用JsonConvert.DeserializeObject
方法將JSON轉換爲類對象,如下所示。
var result = JsonConvert.DeserializeObject<RoleData>(JSON_Response);
我正在使用Android Studio。你可以分享有關安裝https://github.com/FasterXML/jackson的指導原則嗎? – Pankaj