如何使用对象映射器解析json字符串?

时间:2015-06-23 11:51:09

标签: android json jsonp

这是我解析api响应的模型类。

Model.class

public class ModelReminder extends WebRequest implements IWebRequest {

    private static final String CLASS_TAG = ModelReminder.class.getSimpleName();

    // Class member
    private int mUserId;
    private WebAPIResponse mWebAPIResponse;

    public ModelReminder(String strUrlEndPoint, IUIDelegate uiDelegate,
            WeakReference<Context> appContext,
            IWebServiceRequestCallback webServiceRequestCallback) {
        super(strUrlEndPoint, uiDelegate, appContext, webServiceRequestCallback);
    }

    @Override
    public String parseResponse(String strResponseString) {
        strResponseString = strResponseString.trim();

        if (MBUtil.isEmpty(strResponseString)) {
            return "";
        }

        String errMsg = "";

        try {

            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);

            if (!objectMapper.canDeserialize(objectMapper.constructType(WebAPIResponse.class))) {
                return getAppContext().getString(R.string.msg_error_in_reading_format);
            }

            WebAPIResponse webAPIResponse = objectMapper.readValue(strResponseString, WebAPIResponse.class);
            this.mWebAPIResponse = webAPIResponse;

        } catch (Exception e) {
            Log.e(CLASS_TAG, e.getMessage());
            errMsg = e.getMessage();
        }
        return errMsg;
    }

    @Override
    public JSONObject buildRequestBody() {
        JSONObject jsonObject = new JSONObject();
        Context context = getAppContext();
        if(context == null) {
            return jsonObject;
        }

        try {

            JSONObject authenticationJsonObject = new JSONObject();
            authenticationJsonObject.put(context.getString(R.string.key_points_uid), mUserId);
            return authenticationJsonObject;

        } catch (Exception e) {
            Log.e(CLASS_TAG, e.getMessage());
        }
        return jsonObject;
    }

    public WebAPIResponse getWebAPIResponse() {
        return mWebAPIResponse;
    }

    public void setWebAPIResponse(WebAPIResponse mWebAPIResponse) {
        this.mWebAPIResponse = mWebAPIResponse;
    }

    public int getUserId() {
        return mUserId;
    }

    public void setUserId(int mUserId) {
        this.mUserId = mUserId;
    }

    public static class WebAPIResponse {
        //TODO: What to do here?

    }

}

我收到如下的响应字符串。

{ "0": { "remid": "3", "title": "roundup for Self" }, 
  "1": { "remid": "4", "title": "anthrax for Self" }, 
  "2": { "remid": "5", "title": "sevendust for Self"}, ...
}

我想创建一个映射类来解析上面的JSON字符串。我应该在WebAPIResponse课程中做什么?

0 个答案:

没有答案