简体   繁体   中英

write json to String instead of file in java

I am using jackson for converting POJO to JSON

     User user = new User();
    user.setAge(25);
    user.setName("Shahid");

     ObjectMapper mapper= new ObjectMapper();
     mapper.writeValue("D:/test.json", user);

instead of writing it to file , I want to write it to on String variable ( jsonString ) . So that I get the result as follow.

String jsonString= "{"name" : "Shahid","age" : 25}";

You can try,

mapper.writeValueAsString(user).

Please refer documentation for more details.

You can try this:

OutputStream os = new ByteArrayOutputStream();
mapper.writeValue(os, user);
String json = os.toString();

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM