如何在Kotlin中手动解析JSON?

时间:2017-11-16 16:06:47

标签: android json kotlin

我想在Kotlin中手动解析JSON响应。因为我正在获得具有一些共同字段的复杂JSON响应。例如,我收到了低于响应。

{ 
  status: "success/false"
  apiId: 6
  message: "Error msg if any"
  .
  .   
  .    // Here comes some JSON with complex structure where some fields are
  .    // missing/omitted. Sometime array is missing/response in array is
  .    // getting changed, getting lot of unwanted stuff Or whatever you can
  .    // think. And because of this I need to parse it manually.
  .
}

现在我如何在data类Kotlin中手动解析这种类型的响应?还有一件事我想知道,我可以在响应中使用任何基类用于公共字段吗?

3 个答案:

答案 0 :(得分:0)

应该是这样的:

data class Response(val status: String, val apiId: Int , val message: String)

答案 1 :(得分:0)

jackson-databind具有@JsonIgnoreProperties(ignoreUnknown=true)注释,可以忽略不需要的json字段。那么你需要做的就是编写一个如下所示的数据类

@JsonIgnoreProperties(ignoreUnknown=true)
data class Response(val status: String, val apiId: Int, val message: String)

答案 2 :(得分:0)

我发现了这个code in googlemaps repository,它提供了无需第三方库就可以手动解析JSON对象的功能。它解析JSON坐标,似乎很可行。下面是输入JSON和代码的示例:

[{"lat" : 51.5145160, "lng" : -0.1270060 },
{ "lat" : 51.5064490, "lng" : -0.1244260, "title" : "Corinthia Hotel London", "snippet": "Whitehall Pl"},
{ "lat" : 51.5097080, "lng" : -0.1200450,  "title" : "Savoy Place", "snippet" : "Covent Garden"},
{ "lat" : 51.5090680, "lng" : -0.1421420, "title" : "Albemarle St", "snippet": "Mayfair"},
{ "lat" : 51.4976080, "lng" : -0.1456320, "title" : " Victoria Square", "snippet": " Belgravia" },
{ "lat" : 51.5046150, "lng" : -0.1473780}]

 /**
 * Returns a list of cluster items read from the provided [inputStream]
 */
@Throws(JSONException::class)
fun read(inputStream: InputStream): List<MyItem> {
    // This matches only once in whole input so Scanner.next returns whole InputStream as a
    // String. http://stackoverflow.com/a/5445161/2183804
    val REGEX_INPUT_BOUNDARY_BEGINNING = "\\A"

    val items = mutableListOf<MyItem>()
    val json = Scanner(inputStream)
        .useDelimiter(REGEX_INPUT_BOUNDARY_BEGINNING).next()
    val array = JSONArray(json)
    for (i in 0 until array.length()) {
        var title: String? = null
        var snippet: String? = null
        val `object` = array.getJSONObject(i)
        val lat = `object`.getDouble("lat")
        val lng = `object`.getDouble("lng")
        if (!`object`.isNull("title")) {
            title = `object`.getString("title")
        }
        if (!`object`.isNull("snippet")) {
            snippet = `object`.getString("snippet")
        }
        items.add(MyItem(LatLng(lat, lng), title, snippet))
    }
    return items
}

最后一项是:

data class MyItem(val latLng: LatLng, val myTitle: String?, val mySnippet: String?) : ClusterItem