解析 JSON 对象内的 JSON 对象

Parse JSON Object inside JSON Object

我想使用 Retrofit 解析 Json 对象。解析“Phone”和“地址”的最佳方法是什么? 谢谢。

{
    "name": "Miss Piggy",
    "id": "13",
    "companyName": "Muppets, Baby",
    "isFavorite": false,
    "smallImageURL": "https://s3.amazonaws.com/technical-challenge/v3/images/miss-piggy-small.jpg",
    "largeImageURL": "https://s3.amazonaws.com/technical-challenge/v3/images/miss-piggy-large.jpg",
    "emailAddress": "Miss.Piggy@muppetsbaby.com",
    "birthdate": "1987-05-11",
    "phone": {
        "work": "602-225-9543",
        "home": "602-225-9188",
        "mobile": ""
    },
    "address": {
        "street": "3530 E Washington St",
        "city": "Phoenix",
        "state": "AZ",
        "country": "US",
        "zipCode": "85034"
    }
}

您可以使用 JSON 解析库(例如 Gson or Moshi) with the correct retrofit converter 来创建 classes(kotlin 中的数据 classes)来解析嵌入对象.

kotlin 中的一个例子。

回应class

data class Response (
    val name: String,
    val id: String,
    val companyName: String,
    val isFavorite: Boolean,
    val smallImageURL: String,
    val largeImageURL: String,
    val emailAddress: String,
    val birthdate: String,
    val phone: Phone,
    val address: Address) 

地址Class

data class Address (
    val street: String,
    val city: String,
    val state: String,
    val country: String,
    val zipCode: String )

Phone Class

data class Phone (
    val work: String,
    val home: String,
    val mobile: String)

有关详细信息,请查看 Google's Codelab 示例

如果您打算从任何子 JSON 对象获取任何字符串的值,那么使用 Android JAVA 的内置 JSON 解析器可以帮助您没有任何新库。

JSONObject jsonObject = new JSONObject(s);
// extract phone object
JSONObject phoneJsonObject = jsonObject.getJSONObject("phone");
// we can any data of the sub json object of main object
// get string value of work
String valueOfWork = phoneJsonObject.getString("work");

// extract address object
JSONObject addressJsonObject = jsonObject.getJSONObject("address");
// we can any data of the sub json object of main object
// get string value of street
String valueOfStreet = phoneJsonObject.getString("street");

Log.i("Getting Value of Work from Phone Object", valueOfWork);
Log.i("Getting Value of Street from Address Object", valueOfStreet);