Shahid Ghafoor
Shahid Ghafoor

Reputation: 3103

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

Upvotes: 3

Views: 213

Answers (2)

Akshay
Akshay

Reputation: 350

You can try this:

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

Upvotes: 1

Dark Knight
Dark Knight

Reputation: 8347

You can try,

mapper.writeValueAsString(user).

Please refer documentation for more details.

Upvotes: 1

Related Questions