8
JsonGenerator generator = 
                new JsonFactory().createJsonGenerator(new JSONWriter(response));
generator.configure(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS, true);

我曾经JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS在 json 中将数字写为字符串。但是,我找不到将布尔值写为字符串的类似功能。

4

2 回答 2

7

我也找不到布尔的类似功能。所以,我建议为布尔字段编写新的序列化器和反序列化器。

看我的例子:

public class JacksonProgram {

    public static void main(String[] args) throws IOException {
        Foo foo = new Foo();
        foo.setB(true);
        foo.setS("Test");
        foo.setI(39);

        ObjectMapper objectMapper = new ObjectMapper();
        JsonFactory jsonFactory = new JsonFactory();

        StringWriter stringWriter = new StringWriter();
        JsonGenerator jsonGenerator = jsonFactory.createGenerator(stringWriter);
        jsonGenerator.enable(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS);
        objectMapper.writeValue(jsonGenerator, foo);
        System.out.println(stringWriter);

        JsonParser jsonParser = jsonFactory.createJsonParser(stringWriter.toString());
        Foo value = objectMapper.readValue(jsonParser, Foo.class);
        System.out.println(value);
    }
}

class BooleanSerializer extends JsonSerializer<Boolean> {

    @Override
    public void serialize(Boolean value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
        jsonGenerator.writeString(value.toString());
    }
}

class BooleanDeserializer extends JsonDeserializer<Boolean> {

    public Boolean deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        return Boolean.valueOf(jsonParser.getValueAsString());
    }
}

class Foo {

    @JsonSerialize(using = BooleanSerializer.class)
    @JsonDeserialize(using = BooleanDeserializer.class)
    private boolean b;
    private String s;
    private int i;

    public boolean isB() {
        return b;
    }

    public void setB(boolean b) {
        this.b = b;
    }

    public String getS() {
        return s;
    }

    public void setS(String s) {
        this.s = s;
    }

    public int getI() {
        return i;
    }

    public void setI(int i) {
        this.i = i;
    }

    @Override
    public String toString() {
        return "Foo [b=" + b + ", s=" + s + ", i=" + i + "]";
    }
}

输出:

{"b":"true","s":"Test","i":"39"}
Foo [b=true, s=Test, i=39]

编辑

我认为,您应该将SimpleModule配置添加到ObjectMapper

SimpleModule simpleModule = new SimpleModule("BooleanModule");
simpleModule.addSerializer(Boolean.class, new BooleanSerializer());
simpleModule.addDeserializer(Boolean.class, new BooleanDeserializer());

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(simpleModule);

现在,您应该能够序列化 boolean/Object List-s 和 Map-s。

于 2013-05-15T13:15:49.070 回答
0

我所知道的工作 json 字符串看起来像这样:

string json = "
{
"somestring": "some string value"
"someboolean": true
}
";

使用特定于您使用的语言的多行语法。

于 2018-04-19T00:25:07.713 回答