8
@NotNull
@JsonTypeInfo(
    use = JsonTypeInfo.Id.NAME,
    include = JsonTypeInfo.As.EXTERNAL_PROPERTY,
    property = "type")
@JsonSubTypes(value = {@JsonSubTypes.Type(value = SimpleGrantedAuthority.class)})
private List<GrantedAuthority> authorityList;

Above is my attribute which is a Spring Security interface for setting/authorizing users. In my test, I use the statement below to serialize to JSON as it'll be a an array or list within the JSON request body injected using camel content enricher.

String jsonObject =  mapper.writeValueAsString(accountDetails);

I get this error because of that above line:

com.fasterxml.jackson.core.JsonGenerationException: Can not write a field name, expecting a value

    at com.fasterxml.jackson.core.JsonGenerator._reportError(JsonGenerator.java:1897)
    at com.fasterxml.jackson.core.json.WriterBasedJsonGenerator.writeFieldName(WriterBasedJsonGenerator.java:126)
    at com.fasterxml.jackson.core.json.JsonGeneratorImpl.writeStringField(JsonGeneratorImpl.java:202)
    at com.fasterxml.jackson.databind.jsontype.impl.AsExternalTypeSerializer._writeObjectSuffix(AsExternalTypeSerializer.java:163)
    at com.fasterxml.jackson.databind.jsontype.impl.AsExternalTypeSerializer.writeTypeSuffixForObject(AsExternalTypeSerializer.java:88)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeWithType(BeanSerializerBase.java:584)
    at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serializeContents(CollectionSerializer.java:151)
    at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serialize(CollectionSerializer.java:112)
    at com.fasterxml.jackson.databind.ser.std.CollectionSerializer.serialize(CollectionSerializer.java:25)
    at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:704)
    at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:690)
    at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:155)
    at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:292)
    at com.fasterxml.jackson.databind.ObjectMapper._configAndWriteValue(ObjectMapper.java:3681)
    at com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(ObjectMapper.java:3057)
    at com.sammy.controller.HomeControllerTest.checkCreateUser(HomeControllerTest.java:74)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    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.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    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.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

Any help will be much appreciated.

Sammy65
  • 627
  • 2
  • 12
  • 28

3 Answers3

18

If you've found this page because you're trying to Serialize an object in Spring's JsonSerializer using the JsonGenerator.write(String/Number)Field function and see the com.fasterxml.jackson.core.JsonGenerationException: Can not write a field name, expecting a value error even though you've supplied a value:

Make sure that before you call writeField you've called JsonGenerator.writeStartObject();

anon
  • 4,163
  • 3
  • 29
  • 26
0

Change this

@JsonSubTypes(value = {
            @JsonSubTypes.Type(value = SimpleGrantedAuthority.class)
        }
)

to this,

@JsonSubTypes({
@JsonSubTypes.Type(value = SimpleGrantedAuthority.class, name = "ROLE_ADMIN"),
})

Here name parameter of the JsonSubTypes should be the name you used in the JSON object to identify that sub class.

Dulaj Atapattu
  • 448
  • 6
  • 23
  • `UserAccountDetails(..., authorityList=[ROLE_ADMIN, ROLE_USER])` is how the POJO prints it out. And, this is how I load it in: `List authorities = new ArrayList<>(); authorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));` so not sure which name to use as it still throws the same error when I use the authorities name of the list. Also, the Json is supposed to just show an authorityList array object. – Sammy65 Jun 03 '17 at 16:25
  • @Sammy65 your comment is not clear to me. Then you can use name = "ROLE_ADMIN". Please see the edited answer. – Dulaj Atapattu Jun 04 '17 at 04:31
  • @Sammy65 And can you provide more piece of code? When do you get the error? Serializing or deserializing? – Dulaj Atapattu Jun 04 '17 at 04:41
  • It's when I try to serialize the object using those annotations. When I don't, I get a different error which I've asked a question about also from this link: [ObjectMapper](https://stackoverflow.com/questions/44294830/org-springframework-http-converter-httpmessagenotreadableexception) – Sammy65 Jun 04 '17 at 20:52
0

If you want to serialize List< GrantedAuthority>, you can try to customize a serializer and then register the serializer directly on the class

Serializer


public class AuthoritySerializer extends JsonSerializer<SysUser> {

    @Override
    public void serialize(SysUser sysUser, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {      
       List<String> authorities = sysUser.getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList());
        jsonGenerator.writeStartObject();
        jsonGenerator.writeObjectField("id", sysUser.getId());
        jsonGenerator.writeStringField("username", sysUser.getUsername());
        jsonGenerator.writeStringField("password", sysUser.getPassword());
        jsonGenerator.writeFieldName("authorities");
        jsonGenerator.writeArray(authorities.toArray(new String[0]), 0, authorities.size());
        jsonGenerator.writeEndObject();
       
    }
}
orzzsy
  • 11
  • 2