Jackson Parse to Java

primitive type

{
    "admin_email": "abc@123.com",
    "admin_password": "abc123"
}
  • 只能取得第一層的參數,無法取得第二層的參數
  • 如果使用optString(),會視為null並轉換空字串;如果使用getString(),會視為null拋出Exception
  • 如果使用optInt(),會使用預設值0;如果使用optInt(),會拋出異常

parse array and list

array -> object

Ref: java - How to parse JSON Array (Not Json Object) in Android - Stack Overflow

[
    {
        "key": "account",
        "value": "Peter Lin"
    },
    {
        "key": "boolean",
        "value": "false"
    }
]

java:

JSONArray jsonArrayString = new JSONArray(reqJson);
for (int i = 0; i < jsonArrayString.length(); i++) {
    JSONObject jsonObject = jsonArrayString.optJSONObject(i);
    String key = jsonObject.optString("key");
    String value = jsonObject.optString("value");
    log.info(key);
    log.info(value);
}


object -> array

{
    "patent_ids": [
        "patent-1",
        "patent-2",
        "patent-3"
    ],
    "field_ids": [
        "field-1",
        "field-2",
        "field-3"
    ]
}

java:

TypeReference<?> typeReference = new TypeReference<List<String>>() { };
List<String> patentIds = (List<String>) JacksonJSONUtils.readValue(jsonPid, typeReference);
List<String> fieldIds = (List<String>) JacksonJSONUtils.readValue(jsonFid, typeReference);


parse bean object

use Gson:

Person person = new Gson().fromJson(json, Person.class);

Ref:

TypeReference

將數據反序列化成物件對象,使用typereference指定輸入數據為何種泛型格式

Ref:

Reference

Official Documentations:

compare:

Project:

Tutorial: