如何使用objectMapper解析没有任何键值的json数组?

时间:2015-06-26 15:18:19

标签: android json jsonp

我正在获得这样的json响应字符串。

 [
   "assets\/imgs\/choicelogos\/choice-logo.jpg",
   "assets\/imgs\/choicelogos\/family-health-logo.jpg",
   "assets\/imgs\/choicelogos\/four-corners-logo.jpg",
   "assets\/imgs\/choicelogos\/grady-logo.jpg",
   "assets\/imgs\/choicelogos\/hands-logo.jpg",
   "assets\/imgs\/choicelogos\/morehouse-logo.jpg",
   "assets\/imgs\/choicelogos\/smc-logo.jpg"
]

这是我使用ObjectMapper类解析此字符串的方法。

public String parseResponse(String strResponseString) { 
        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);
            }

            TypeFactory typeFactory = objectMapper.getTypeFactory();
            List<WebAPIResponse> someClassList = objectMapper.readValue(strResponseString, typeFactory.constructCollectionType(List.class, WebAPIResponse.class));

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

但我无法解析。它正在抛出errorMsg = null。请任何人帮助我改变什么?

1 个答案:

答案 0 :(得分:1)

以下是此问题的解决方案。

@JsonIgnoreProperties(ignoreUnknown = true)
    private List<String> mWebAPIResponse;

@Override
    public String parseResponse(String strResponseString) {

        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);
            }

            List<String> webAPIResponse = objectMapper.readValue(strResponseString, new TypeReference<ArrayList<String>>() {});
            this.mWebAPIResponse = webAPIResponse;

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