ripper234
ripper234

Reputation: 230038

How do I convert an object to JSON representation

Oddly enough, I didn't find this.

What's the simplest way to convert an object to a JSON string? (Edge cases like loops in the object graphs aren't of much interest to me. Let's find a solution to the simple case of class A that contains some objects of classes B,C,D and some primitives).

Basic collection support is a must.

Upvotes: 5

Views: 4367

Answers (4)

ripper234
ripper234

Reputation: 230038

Heh, I discovered/remembered what we are already using for this.

ObjectMapper from CodeHaus

The code looks like this - super simple:

Object obj = ...
String result = new ObjectMapper().writeValueAsString(obj);

Upvotes: 5

haylem
haylem

Reputation: 22663

See answer here: Javascript to Java using JSON

The answer applies both ways, they're bi-directional.

Upvotes: 2

willcodejavaforfood
willcodejavaforfood

Reputation: 44063

I'd recommend JAXB + Jackson. Look at this question for more details.

Upvotes: 2

NimChimpsky
NimChimpsky

Reputation: 47290

Gson from google is good for me . It works with collections and generics and converts both ways.

Upvotes: 2

Related Questions