1 /* 2 * Copyright (C) 2023 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.tools.metalava.apilevels 18 19 import com.google.gson.GsonBuilder 20 import java.io.PrintWriter 21 22 /** Handles converting an [Api] to a JSON version history file. */ 23 internal class ApiJsonPrinter : ApiPrinter { printnull24 override fun print(api: Api, writer: PrintWriter) { 25 val gson = GsonBuilder().disableHtmlEscaping().create() 26 val json = api.toJson() 27 gson.toJson(json, writer) 28 } 29 toStringnull30 override fun toString() = "JSON" 31 32 private fun Api.toJson() = classes.map { it.toJson() } 33 toJsonnull34 private fun ApiClass.toJson() = 35 toJson("class") + 36 mapOf( 37 "methods" to methods.sorted().map { it.toJson("method") }, <lambda>null38 "fields" to fields.sorted().map { it.toJson("field") } 39 ) 40 toJsonnull41 private fun ApiElement.toJson(elementType: String) = 42 mapOf( 43 elementType to name, 44 "addedIn" to since.toString(), 45 "deprecatedIn" to deprecatedIn?.toString(), 46 ) 47 } 48