how to convert json object into class object
How to con开发者_C百科vert this json clsError and userId values:
String temp = "{"clsError":{"ErrorCode":110,"ErrorDescription":" Request Added"},"UserID":36}"
And pass them as parameters:
clsError errorObject=new clsError(UserID,clsError);
First use this: http://developer.android.com/reference/org/json/JSONObject.html#JSONObject(java.lang.String)
JSONObject tempJson = new JSONObject(temp);
JSONObject clsErrorJson = tempJson.getJSONObject("clsError");
clsError errorObject = new clsError(tempJson.getString("UserID"),
clsErrorJson.getInt("clsError") + ": "
+ clsErrorJson.getString("ErrorDescription"));
that is basically it. but i was not sure about the second parameter of the clsError constructor. i just assumed it is a string in my example :) but this should give you the idea how to do this. and you will have to surround that with try/catch. eclipse will tell you how :)
I've found jackson's ObjectMapper to be extremely helpful in cases like this.
ObjectMapper objectMapper = new ObjectMapper();
clsError error = objectMapper.readValue(temp, clsError.class));
You can use jQuery extend method to wrap your json into javascript object as below:
function clsError(ErrorCode,ErrorDescription,UserID){
this.ErrorCode=ErrorCode;
this.ErrorDescription=ErrorDescription;
this.UserID=UserID;
}
String temp="{"clsError":{"ErrorCode":110,"ErrorDescription":" Request Added"},"UserID":36}"
var obj = $.extend(new clsError(), temp);
精彩评论