images
29/09/2020 09:26 am

Java JSON

JavaScript Object Notation (JSON) is an open standard file format, and data interchange format, that uses human-readable text to store and transmit data objects consisting of attribute–value pairs and array data types (or any other serializable value)

JavaScript Object Notation (JSON) is an open standard file format, and data interchange format, that uses human-readable text to store and transmit data objects consisting of attribute–value pairs and array data types (or any other serializable value).

Video Object:

{

  "id": 10,

  "title": "this is a java tech",

  "description": "Most advanced techniques",

  "createdAt": "2020-09-04T21:32:03.745",

  "modifiedAt": "2020-09-04T21:32:03.745",

  "authorId": "hoang"

}


Java JSON Type


JSON

Java

string

java.lang.String

number

java.lang.Number

true|false

java.lang.Boolean

null

null

array

java.util.List

object

java.util.Map


JSON


Video Array 2 items:

[{

  "id": 10,

  "title": "this is Java",

  "description": "Most advanced techniques",

  "createdAt": "2020-09-03T22:11:03.331",

  "modifiedAt": "2020-09-03T22:12:03.321",

  "authorId": "techzone"

},

{

  "id": 11,

  "title": "this is Python",

  "description": "Most advanced techniques",

  "createdAt": "2020-09-04T21:32:03.745",

  "modifiedAt": "2020-09-04T21:32:03.745",

  "authorId": "hoang"

}]


Nested Object: author


{

  "id": 10,

  "title": "this is Java",

  "description": "Most advanced techniques",

  "createdAt": "2020-09-03T22:11:03.331",

  "modifiedAt": "2020-09-03T22:12:03.321",

  "author": {

id": “techzonefun",

page": “fb.com/techzonefun"

  }

}


Java With JSON


Sử dụng Jackson, JSON để làm việc với JSON trong Java


- Serialize Object to JSON

- Deserialize String JSON to Object


Java với JSON Lib


Để sử dụng JSON library trong Java ta cần Import thư viện sử dụng Gradle hay Maven như sau:

// Gradle: 

compile 'org.json:json:20180130'


// Maven:

<dependency>

    <groupId>org.json</groupId>

    <artifactId>json</artifactId>

    <version>20180130</version>

</dependency>


Tạo json string:


JSONObject jsonObject = new JSONObject();

jsonObject.put("name", "techzonefun");

jsonObject.put("fb", "https://fb.com/techzonefun");

System.out.println(jsonObject);


Output:

{"name":"techzonefun","fb":"https://fb.com/techzonefun"}


Tạo json string từ Map


Map<String, Object> hashMap = new HashMap<>();

hashMap.put("name", "techzonefun");

hashMap.put("fb", "https://fb.com/techzonefun");


JSONObject jsonObject = new JSONObject(hashMap);

System.out.println(jsonObject);


Output:

{"name":"techzonefun","fb":"https://fb.com/techzonefun"}


Tạo json object từ String


JSONObject jo = new JSONObject("{\"name\":\"techzonefun\",\"fb\":\"https://fb.com/techzonefun\"}”)


Xử lý lấy thông tin từ Json Object


String json = "{\"name\":\"techzonefun\",

    \"fb\":\"https://fb.com/techzonefun\",

   \"data\":{\"name\": \"java\"}}";


JSONObject jsonObject = new JSONObject(json)


jsonObject.get(“name");

jsonObject.get(“data");

jsonObject.getJSONObject("data");


Java với Jackson


Để sử dụng Jackson trong Java ta cần Import thư viện sử dụng Gradle hay Maven như sau:


// Gradle:

compile group: 'com.fasterxml.jackson.core', name: 'jackson-databind', version: '2.9.8'

compile group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-jsr310', version: '2.4.0'


// Maven:

<dependency>

    <groupId>com.fasterxml.jackson.core</groupId>

    <artifactId>jackson-databind</artifactId>

    <version>2.9.8</version>

</dependency>

<dependency>

    <groupId>com.fasterxml.jackson.datatype</groupId>

    <artifactId>jackson-datatype-jsr310</artifactId>

    <version>2.4.0</version>

</dependency>


Serialize Object to JSON


Sử dụng ObjectMapper.writeValueAsString để serialize 1 object thành chuỗi JSON string:


ObjectMapper objectMapper = new ObjectMapper();

objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

objectMapper.registerModule(new JSR310Module());

Video video = new Video("hoang", "this is a java tech", "Most advanced technique");

String json = objectMapper.writeValueAsString(video);

System.out.println(json);


Serialize LocalDateTime to JSON


{"id":null,"title":"this is a java tech","description":"Most advanced technique",

"createdAt":{"hour":21,"minute":54,"second":57,"nano":405000000,"dayOfYear":248,"dayOfWeek":"FRIDAY","month":"SEPTEMBER","dayOfMonth":4,"year":2020,"monthValue":9,"chronology":{"id":"ISO","calendarType":"iso8601"}},

"modifiedAt":{"hour":21,"minute":54,"second":57,"nano":405000000,"dayOfYear":248,"dayOfWeek":"FRIDAY","month":"SEPTEMBER","dayOfMonth":4,"year":2020,"monthValue":9,"chronology":{"id":"ISO","calendarType":"iso8601"}},

"authorId":"hoang"}


Khai báo JSR310Module như sau:


ObjectMapper objectMapper = new ObjectMapper();

objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

objectMapper.registerModule(new JSR310Module());

Video video = new Video("hoang", "this is a java tech", "Most advanced technique");

String json = objectMapper.writeValueAsString(video);

System.out.println(json);


Hãy xem kết quả:


{

   "title":"this is a java tech",

   "description":"Most advanced technique",

   "createdAt":"2020-09-04T21:59:03.464",

   "modifiedAt":"2020-09-04T21:59:03.464",

   "authorId":"hoang"

}


Serialize Array to JSON


ObjectMapper objectMapper = new ObjectMapper();

objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

objectMapper.registerModule(new JSR310Module());

List<Video> videos = new ArrayList();

// add video to list

String json = objectMapper.writeValueAsString(videos);

System.out.println(json);


Serialize Map to JSON

ObjectMapper objectMapper = new ObjectMapper();

Map<String, Object> map = new HashMap();

map.put(“key1”, “value1”);

map.put(“key2”, “value2”);

String json = objectMapper.writeValueAsString(map);

System.out.println(json);


// {“key1”: “value1”, “key2”:”value2”}


Deserialize String JSON to Object


Ta có xâu JSON sau. Làm sao có thể convert thành Object Video:

{

   "id":null,

   "title":"this is a java tech",

   "description":"Most advanced technique",

   "createdAt":"2020-09-04T21:59:03.464",

   "modifiedAt":"2020-09-04T21:59:03.464",

   "authorId":"hoang"

}


Video video = objectMapper.readValue(json, Video.class);


Deserialize String JSON to Array


Ta có xâu JSON sau. Làm sao có thể convert thành List Video:


[

   {

      "id":"abc”,

      "title":"this is a java tech",

      "description":"Most advanced technique",

      "createdAt":"2020-09-03T21:59:03.464",

      "modifiedAt":"2020-09-03T21:59:03.464",

      "authorId":"hoang"

   },

   {

      "id":"def”,

      "title":"this is a python tech",

      "description":"Most advanced technique",

      "createdAt":"2020-09-04T11:59:03.464",

      "modifiedAt":"2020-09-04T11:59:03.464",

      "authorId":"hoang"

   }

]


List<Video> videos = objectMapper.readValue(json, new TypeReference<List<Video>>(){});


Deserialize String JSON to Map


Ta có xâu JSON sau. Làm sao có thể convert thành Map:


// {“key1”: “value1”, “key2”:”value2”}


Map<String, Object> map = objectMapper.readValue(json, Map.class);


Mời các bạn đọc thêm bài Các cách lập trình đa luồng trong Java - Phần 1


- Tech Zone -


Thư giãn chút nào!!!

Bài viết liên quan