Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

write json to String instead of file in java

Tags:

java

json

jackson

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}";

like image 583
Shahid Ghafoor Avatar asked Dec 19 '25 16:12

Shahid Ghafoor


1 Answers

You can try,

mapper.writeValueAsString(user).

Please refer documentation for more details.

like image 89
Dark Knight Avatar answered Dec 22 '25 06:12

Dark Knight



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!