解决对象与JSON解析时属性不对应+空字符串+枚举的问题

在将JSON串解析为对象时,如果属性不对应或者枚举为空字符串时,均会导致解析错误,此时可通过几个配置解决,直接上代码

package com.dms.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtils {

	public static String encode(Object obj) {
		ObjectMapper om = new ObjectMapper();
		ByteArrayOutputStream baos = null;
		try {
			baos = new ByteArrayOutputStream();
			JsonGenerator generator = om.getFactory().createGenerator(baos,
					JsonEncoding.UTF8);
			generator.writeObject(obj);
			String result = new String(baos.toByteArray(), "utf-8");
			return result;
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
				if (baos != null) {
					baos.close();
				}
			} catch (IOException e) {
			}
		}
	}

	public static  T decode(String content, Class valueType) {
		ObjectMapper om = new ObjectMapper();
		om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		om.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT,
				true);
		om.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL,
				true);
		try {
			return om.readValue(content, valueType);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}

在将包含对象数组的JSON解析为List时,咱没发现有什么好的方法,可先解析为数组,再转换为List

Image[] imageList1 = JsonUtils.decode((String) router.requestGet(),Image[].class);


你可能感兴趣的:(JSON)