简体   繁体   中英

How to marshal/unmarshal JSON in a Java application?

Assuming that I have the following JSON string:

{
  "1": {
    "id": "12",
    "name": "xyz"
  },
  "2": {
    "id": "12",
    "name": "xyz"
  },
  "3": {
    "id": "12",
    "name": "xyz"
  },
  "4": {
    "id": "12",
    "name": "xyz"
  },
  "5": {
    "id": "12",
    "name": "xyz"
  },
  "6": {
    "id": "12",
    "name": "xyz"
  }
}

How would one go about creating this JSON structure from within a Java application? Are there any good libraries to aid in marshaling and unmarshaling JSON for Java?

There are several popular libraries: jackson already mentioned here, gson, org.json and others.
There are also some convenience libraries that not dealing with serialization but can be useful for parsing, for example https://github.com/jayway/JsonPath . It possibly (didn't test it by myself) can be a bit slower but more convenient.
If you do not handle of tons of json documents per second or very large/comples documents (or both), you probably can select any library that looks simple for you. If you deal with cases that I mentioned, you'll need to read some performance test results in google or run your own, if possible.

With libraries like jackson-core , you can easily transform json into an object representation and vice versa easily and efficiently with minimal code.

For example, the JSON you showed would be a Map<String,SomeObject> where SomeObject would be represented as follows:

public class SomeObject {
  private String id;
  private String name;
}

The map would be populated as follows, assuming a constructor that takes id and name for the map entry's value.

Map<String, SomeObject> map = new LinkedHashMap<>();
map.put( "1", new SomeObject( "12", "xyz" ) );
map.put( "2", new SomeObject( "12", "xyz" ) );
map.put( "3", new SomeObject( "12", "xyz" ) );
map.put( "4", new SomeObject( "12", "xyz" ) );
map.put( "5", new SomeObject( "12", "xyz" ) );
map.put( "6", new SomeObject( "12", "xyz" ) );

Now to get the JSON string from Java:

String output = new ObjectMapper().writeValueAsString( map );

If you had the JSON string and you wanted to get the object representation:

ObjectMapper mapper = new ObjectMapper();
Map<String, SomeObject> map = new LinkedHashMap<>();
map = mapper.readValue( json, new TypeReference<Map<String,SomeObject>>(){} );   

Obviously this is a basic overview. It'd be wise to read the documentation for the Jackson API hosted on their github here .

I would to recommend another library: fastjson . it's simple, faster and smaller, comparing Jackson.

Map<String, Object> map = JSON.parseObject(json, Map.class);

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