【web開發】fastjackson轉換json字串為bean時忽略未知欄位

yingxian_Fei發表於2017-11-24

在做json轉換為bean物件時經常遇到有時json中新增了欄位,但是bean中未及時增加適配的屬性,導致pojo轉換失敗的問題,在使用faskjackson時可以在bean的類上使用@JsonIgnoreProperties(ignoreUnknown = true)來忽略未能識別的欄位。如下為一個測試用例的主要實現(其中未包含faskjackson轉換json為bean的部分,這部分請自行實現):

package api.landsem.tester.misc;

import org.apache.log4j.Logger;
import org.junit.Test;
import org.springframework.util.Assert;

import api.landsem.tester.media.BaseTester;
import api.landsem.utils.LocalStringUtils;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

public class Json2BeanTester extends BaseTester{
	private final static Logger logger = Logger.getLogger(Json2BeanTester.class);
	
	@JsonIgnoreProperties(ignoreUnknown = true)
	public static class Ta {
		private String payload;
		private String messagetype;
		private String timestamp;
		

		public String getPayload() {
			return payload;
		}

		public void setPayload(String payload) {
			this.payload = payload;
		}

		public String getMessagetype() {
			return messagetype;
		}

		public void setMessagetype(String messagetype) {
			this.messagetype = messagetype;
		}

		public String getTimestamp() {
			return timestamp;
		}

		public void setTimestamp(String timestamp) {
			this.timestamp = timestamp;
		}

		@Override
		public String toString() {
			return "Ta [payload=" + payload + ", messagetype=" + messagetype
					+ ", timestamp=" + timestamp + "]";
		}
		
		/*
		private String messageid;

		public String getMessageid() {
			return messageid;
		}

		public void setMessageid(String messageid) {
			this.messageid = messageid;
		}	
		 */
		
		
	}

	@Test
	public void test() {
		final String json = "{\"payload\":\"eyJsYXN0VGltZSI6IjIwMTctMTEtMjQgMTQ6Mzg6MjEuMTI3IiwidGltZSI6IjIwMTctMTEtMjQgMTQ6Mzk6MDYuNDUyIiwicHJvZHVjdEtleSI6InByTTFDSlNuVXBOIiwiZGV2aWNlTmFtZSI6Ijg2OTQ0OTAyMTk5MzE3NCIsInN0YXR1cyI6Im9mZmxpbmUifQ==\",\"messagetype\":\"status\",\"messageid\":933948069962403840,\"timestamp\":1511505546}";
		Ta ta = (Ta) LocalStringUtils.jsonToObject(json, Ta.class);
		Assert.notNull(ta, "Convert error!");
		logger.info("bean="+ta.toString());
	}
}

如上述示例所述,json中包含一個messageid的欄位,該欄位在bean實體類Ta中不存在,如果去掉@JsonIgnoreProperties(ignoreUnknown = true)註解,那麼轉換時將報如下錯誤:

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "messageid" (class api.landsem.tester.misc.Json2BeanTester$Ta), not marked as ignorable (3 known properties: "messagetype", "payload", "timestamp"])
 at [Source: {"payload":"eyJsYXN0VGltZSI6IjIwMTctMTEtMjQgMTQ6Mzg6MjEuMTI3IiwidGltZSI6IjIwMTctMTEtMjQgMTQ6Mzk6MDYuNDUyIiwicHJvZHVjdEtleSI6InByTTFDSlNuVXBOIiwiZGV2aWNlTmFtZSI6Ijg2OTQ0OTAyMTk5MzE3NCIsInN0YXR1cyI6Im9mZmxpbmUifQ==","messagetype":"status","messageid":933948069962403840,"timestamp":1511505546}; line: 1, column: 268] (through reference chain: api.landsem.tester.misc.Json2BeanTester$Ta["messageid"])
	at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:62)
	at com.fasterxml.jackson.databind.DeserializationContext.handleUnknownProperty(DeserializationContext.java:834)
	at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:1093)
	at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownProperty(BeanDeserializerBase.java:1485)
	at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.handleUnknownVanilla(BeanDeserializerBase.java:1463)
	at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:282)
	at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:140)
	at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3798)
	at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2842)
	at api.landsem.utils.LocalStringUtils.jsonToObject(LocalStringUtils.java:70)
	at api.landsem.tester.misc.Json2BeanTester.test(Json2BeanTester.java:72)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:606)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
	at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
	at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
	at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
	at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
	at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
	at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
	at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)


相關文章