JSONUtil

JSONUtil

Introduction

JSONUtil is a collection of static shortcut methods for JSONObject and JSONArray. In the previous chapters, we have introduced some utility methods. In this chapter, we will provide some additional information.

Usage

Creating JSON Strings

JSONUtil.toJsonStr can directly convert any object (Bean, Map, collection, etc.) to a JSON string. If the object is an ordered Map or other similar objects, the resulting JSON string will also be ordered.

SortedMap<Object, Object> sortedMap = new TreeMap<Object, Object>() {
 private static final long serialVersionUID = 1L;
 {
 put("attributes", "a");
 put("b", "b");
 put("c", "c");
 }};

JSONUtil.toJsonStr(sortedMap);

Result:

{"attributes":"a","b":"b","c":"c"}

If we want to obtain a formatted JSON, we can use:

JSONUtil.toJsonPrettyStr(sortedMap);

Result:

{
 "attributes": "a",
 "b": "b",
 "c": "c"
}

Parsing JSON Strings

String jsonStr = "{\"name\":\"Something must have been changed since you leave\"}";
JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
jsonObject.getStr("name");

Converting XML Strings to JSON

String xmlStr = "<sfzh>123</sfzh><sfz>456</sfz><name>aa</name><gender>1</gender>";
JSONObject jsonObject = JSONUtil.parseFromXml(xmlStr);
jsonObject.get("sfzh");
jsonObject.get("name");

Converting JSON to XML

final JSONObject jsonObject = JSONUtil.createObj()
 .set("aaa", "你好")
 .set("key2", "test");
// <aaa>你好</aaa><key2>test</key2>  
final String xmlStr = JSONUtil.toXmlStr(jsonObject);  

JSON to Bean

Let’s define two more complex Beans (including generics):

@Data
public class ADT {
 private List<String> BookingCode;
}

@Data
public class Price {
 private List<List<ADT>> ADT;
}
String json = "{\"ADT\":[[{\"BookingCode\":[\"N\",\"N\"]}]]}";

Price price = JSONUtil.toBean(json, Price.class);

// Get the first booking code in the first ADT list of the Price object
price.getADT().get(0).get(0).getBookingCode().get(0);

Bean to JSON

In Hutool 5.x, a custom annotation @Alias has been added, which allows you to set aliases for Bean fields.

@Data
public class Test {
 private String name;

 @Alias("aliasSex")
 private String sex;

 public static void main(String[] args) {
 Test test = new Test();
 test.setName("handy");
 test.setSex("男");
 // Result: {"name":"handy","aliasSex":"男"}
 String json = JSONUtil.toJsonStr(test);
 }
}

readXXX

These methods are mainly shortcut methods for reading JSON objects from JSON files. They include:

  • readJSON
  • readJSONObject
  • readJSONArray

Other methods

In addition to the commonly used methods above, JSONUtil also provides some auxiliary JSON methods:

  • quote: Escapes all double quotes (using double backslashes for escaping)
  • wrap: Wraps an object, allowing any ordinary object to be converted to a JSON object
  • formatJsonStr: Formats a JSON string. This method does not strictly check the correctness of the JSON format.