My Java class corresponding to the data is as below,
package com.some.package;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.gson.reflect.TypeToken;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.lang.reflect.Type;
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class A {
public static final Type UNMARSHALLER_TYPE = new TypeToken<A>(){}.getType();
@JsonProperty("id")
String id;
@JsonProperty("name")
String name;
@JsonProperty("is_enabled")
boolean isEnabled;
}
Test case class which I have written is failing because the isEnabled is always false
package com.some.package;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.*;
/**
* Created by tanny on 16/11/19.
*/
public class ATest {
private static final String RESPONSE_JSON = "{\"is_enabled\": true, \"name\": \"XXX\", \"id\":\"mock-id\", \"num\":12}";
@Test
public void testAUnmarshaller() throws IOException {
// given
PapiSite payload = new Gson().fromJson(RESPONSE_JSON, A.UNMARSHALLER_TYPE);
// then
assertNotNull(payload);
assertTrue(payload.isEnabled());
assertEquals("XXX", payload.getName());
}
}
Looks like jackson data binder isn't able to parse the json string passed in the test. Any chance I am doing something wrong? Any help or guidance would be much appreciated.
The problem is you are mixing two different libraries jackson
and Gson
, JsonProperty , JsonIgnoreProperties belongs to jackson
and you are trying parse using Gson in test case
Using Gson: You can use @SerializedName while using Gson, you can find more information here about Gson
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class A {
public static final Type UNMARSHALLER_TYPE = new TypeToken<A>(){}.getType();
@SerializedName("id")
String id;
@SerializedName("name")
String name;
@SerializedName("is_enabled")
boolean isEnabled;
}
Using Jackson: you can use ObjectMapper , You can find more information here about jackson
@Test
public void testAUnmarshaller() throws IOException {
// given
ObjectMapper objectMapper = new ObjectMapper();
PapiSite payload = objectMapper.readValue(RESPONSE_JSON, A.class);
// then
assertNotNull(payload);
assertTrue(payload.isEnabled());
assertEquals("XXX", payload.getName());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.