JSONObject
Introduction
JSONObject represents a key-value object in JSON, enclosed by curly braces, with each key-value pair separated by a comma and the key and value separated by a colon. A JSONObject looks like this:
{
"key1":"value1",
"key2":"value2"
}
The key part can be omitted with double quotes, but the value must be enclosed in double quotes if it is a string. If the value is a number or a Boolean value, it does not need to be enclosed in double quotes.
Usage
Creation
JSONObject json1 = JSONUtil.createObj()
.put("a", "value1")
.put("b", "value2")
.put("c", "value3");
JSONUtil.createObj()
is a convenience method for quickly creating a new JSONObject. We can also create it directly using the new
keyword:
JSONObject json1 = new JSONObject();
...
Conversion
- Parsing JSON Strings
String jsonStr = "{\"b\":\"value2\",\"c\":\"value3\",\"a\":\"value1\"}";
// Method 1: Using the utility class to convert
JSONObject jsonObject = JSONUtil.parseObj(jsonStr);
// Method 2: Converting using the new keyword
JSONObject jsonObject2 = new JSONObject(jsonStr);
// Converting a JSONObject to a string (single line)
jsonObject.toString();
// We can also beautify it to display an indented JSON:
jsonObject.toStringPretty();
- Parsing JavaBeans
First, let’s define a Bean:
// Using Lombok for annotations
@Data
public class UserA {
private String name;
private String a;
private Date date;
private List<Seq> sqs;
}
Parsing to JSON:
UserA userA = new UserA();
userA.setName("nameTest");
userA.setDate(new Date());
userA.setSqs(CollectionUtil.newArrayList(new Seq(null), new Seq("seq2")));
// false indicates not to skip null values
JSONObject json = JSONUtil.parseObj(userA, false);
Console.log(json.toStringPretty());
Result:
{
"date": 1585618492295,
"a": null,
"sqs": [
{
"seq": null
},
{
"seq": "seq2"
}
],
"name": "nameTest"
}
As you can see, the order of the output fields is not consistent with the order of the fields in the Bean. If you want to maintain consistency, you can do:
// The second parameter indicates to keep it ordered
JSONObject json = JSONUtil.parseObj(userA, false, true);
Result:
{
"date": 1585618492295,
"a": null,
"sqs": [
{
"seq": null
},
{
"seq": "seq2"
}
],
"name": "nameTest"
}
As you can see, the order of the output fields is inconsistent with the order of the fields in the Bean. To maintain consistency, you can use the following code:
// The second parameter indicates to keep it ordered
JSONObject json = JSONUtil.parseObj(userA, false, true);
Result:
{
"name": "nameTest",
"a": null,
"date": 1585618648523,
"sqs": [
{
"seq": null
},
{
"seq": "seq2"
}
]
}
By default, Hutool outputs dates as timestamps. If you need to customize the date format, you can call:
json.setDateFormat("yyyy-MM-dd HH:mm:ss");
To get the following result:
{
"name": "nameTest",
"a": null,
"date": "2020-03-31 09:41:29",
"sqs": [
{
"seq": null
},
{
"seq": "seq2"
}
]
}