简体   繁体   中英

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.

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);

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

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

See answer here: Javascript to Java using JSON

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM