5

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.

Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
ripper234
  • 222,824
  • 274
  • 634
  • 905

4 Answers4

5

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);
ripper234
  • 222,824
  • 274
  • 634
  • 905
  • That works. One suggestion: if you do this in many places, make sure to reuse ObjectMapper instances... they are expensive to create. – StaxMan Nov 10 '10 at 19:29
  • @StaxMan - indeed, I was just demoing a simple usage. Now, I have to wonder if reusing is thread safe. – ripper234 Nov 10 '10 at 21:56
  • Yes, figured that's the case; but just in case someone wanted to cut'n paste code. And yes, reuse is safe, as per: http://wiki.fasterxml.com/JacksonBestPracticeThreadSafety – StaxMan Nov 11 '10 at 04:06
2

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

NimChimpsky
  • 46,453
  • 60
  • 198
  • 311
2

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

Community
  • 1
  • 1
willcodejavaforfood
  • 43,223
  • 17
  • 81
  • 111
2

See answer here: Javascript to Java using JSON

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

Community
  • 1
  • 1
haylem
  • 22,460
  • 3
  • 67
  • 96