Converting java object having string json filed in to JSON -
in our application 1 database table having result stored json below:
---------------------------------------------------- ------------- content | other fields... ---------------------------------------------------- -------------- "{ \"key\":[\"value1\",\"value2\",\"value3\"]}" | 12 ...
i need fetch , write result file , content
field of set of records single json like: (expected)
[ { "content": { "key": [ "value1", "value2", "value3" ] } } ..... ]
in orresponding java entity put @jsonignore
fields except content
.
class result{ //@jsonignore //otherfields .... @column("content") private string content;//the json string field .... }
but when read db , write file using:
objectwriter writer = new objectmapper().writer().withdefaultprettyprinter(); writer.writevalue(new file(outfile), entitylist);
i got file as: (original)
[ { "content" : "{ \"key\":[\"value1\",\"value2\",\"value3\"]}" } .... ]
you may notice issue. take jason field string , put value key "content", instead of nested jason expected
according how can include raw json in object using jackson? can try annotate content @jsonrawvalue
:
class result { @jsonrawvalue private string content; }
this output:
[ { "content" : { "key":["value1","value2","value3"]} } ]
which semantically want. however, expected outout pretty formatted. can achieved specifying serializer, see convert json string pretty print json output using jackson :
class result { @jsonrawvalue @jsonserialize(using = toprettyjsonserializer.class) private string content; } private static class toprettyjsonserializer extends jsonserializer<string> { @override public void serialize(string string, jsongenerator gen, serializerprovider provider) throws ioexception, jsonprocessingexception { object json = new objectmapper().readvalue(string, object.class); gen.writeobject(json); } }
this outputs:
[ { "content" : { "key" : [ "value1", "value2", "value3" ] } } ]
it not format expected, getting close. hope helps.
Comments
Post a Comment