djechlin
djechlin

Reputation: 60848

Java - convert object to map for use in JSON

I have an object, let's just call it

class Foo {
    String greeting = "Hello";
    int age = 21;
}

That I want to be converted to a map like "greeting" => "Hello", "age" => 21 This will be used as an argument in JSONSerializer.toJSON(arg)

Languages like Perl and Python are very good at this sort of interchange. What's a good practice way to do this in Java?

Upvotes: 0

Views: 317

Answers (2)

Qwerky
Qwerky

Reputation: 18455

You can use Jackson directly to serialise POJOs. Works really well out of the box.

import java.io.Writer;
import java.io.StringWriter;
import org.codehaus.jackson.map.ObjectMapper;

Foo foo = new MyFoo("hello", 21);
ObjectMapper mapper = new ObjectMapper();
Writer writer= new StringWriter();
mapper.writeValue(writer, foo);
String json = writer.toString();
System.out.println(json);

Upvotes: 1

Denys Séguret
Denys Séguret

Reputation: 382454

You don't need to make this conversion prior to the serialization.

Gson would use your object directly and make it a JSON map.

Use this for example :

Gson gson = new GsonBuilder().create();
writer.write(gson.toJson(foo)); // foo is an instance of Foo

Upvotes: 1

Related Questions