使用Gson美化json格式

问题描述

项目中需要对json字符串进行格式化,便于查看.
原始格式:

[{"id":1,"name":"Task1"},{"id":2,"name":"Task2"}]

目标格式:

[
  {
    "id": 1,
    "name": "Task1"
  },
  {
    "id": 2,
    "name": "Task2"
  }
]

解决方案

  1. 添加依赖
implementation "com.google.code.gson:gson:2.8.5"
  1. 格式化函数
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import com.google.gson.JsonParser
fun formatJson(content: String): String {
        val gson = GsonBuilder().setPrettyPrinting().create()
        val jsonParser = JsonParser()
        val jsonElement = jsonParser.parse(content)
        return gson.toJson(jsonElement)
    }

安卓开发技术分享: https://www.jianshu.com/p/442339952f26
点击关注专辑,查看最新技术分享
更多技术总结好文,请关注:「程序园中猿」

《使用Gson美化json格式》

    原文作者:程序园中猿
    原文地址: https://www.jianshu.com/p/eb44c4ec34d9
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞