We can convert a Map to JSON object using the toJSONString() method(static) of org. json. simple. JSONValue.
Converting Java object to JSON In it, create an object of the POJO class, set required values to it using the setter methods. Instantiate the ObjectMapper class. Invoke the writeValueAsString() method by passing the above created POJO object. Retrieve and print the obtained JSON.
We can convert a List to JSON array using the writeValueAsString() method of ObjectMapper class and this method can be used to serialize any Java value as a String.
Pass your Map to ObjectMapper.writeValueAsString(Object value)
It's more efficient than using StringWriter
, according to the docs:
Method that can be used to serialize any Java value as a String. Functionally equivalent to calling writeValue(Writer,Object) with StringWriter and constructing String, but more efficient.
Example
import org.codehaus.jackson.map.ObjectMapper;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class Example {
public static void main(String[] args) throws IOException {
Map<String,String> map = new HashMap<>();
map.put("key1","value1");
map.put("key2","value2");
String mapAsJson = new ObjectMapper().writeValueAsString(map);
System.out.println(mapAsJson);
}
}
You can use a StringWriter.
package test;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
public class StringWriterExample {
private static ObjectMapper objectMapper = new ObjectMapper();
public static void main(String[] args) throws IOException {
Map<String,String> map = new HashMap<>();
map.put("key1","value1");
map.put("key2","value2");
StringWriter stringWriter = new StringWriter();
objectMapper.writeValue(stringWriter, map);
System.out.println(stringWriter.toString());
}
}
produces
{"key2":"value2","key1":"value1"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With