技术问询:如何将Response转换为Model及相关转换疑问
Hey there! Converting JSON responses to strongly-typed models is a staple task in most backend/API work, so let’s break this down step by step using your example JSON. First, let’s dissect the structure of your response, then I’ll show you concrete implementations for a few common languages.
Step 1: Analyze the JSON Structure
First, let’s map out the hierarchy of your response to know what models we need:
- Top-level object: Contains a single
datafield dataobject: Contains three fields:dataList: An array of item objectspageSize: Integer representing the number of items per pagedataSize: Integer representing the total number of items
dataListitems: Each object has string fields:itemCode,itemTypeKey,itemCategoryKey,itemSubCategoryKey,itemName,displayName
Step 2: Implement Models in Popular Languages
Java (Using Jackson Library)
Jackson is the go-to library for JSON processing in Java. Here’s how to define your models and deserialize the JSON:
First, define the model classes:
import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; // Top-level response model public class ItemResponse { @JsonProperty("data") private ItemData data; // Getters and setters (you can use Lombok's @Data annotation to auto-generate these) public ItemData getData() { return data; } public void setData(ItemData data) { this.data = data; } } // Model for the inner "data" object public class ItemData { @JsonProperty("dataList") private List<Item> itemList; @JsonProperty("pageSize") private int pageSize; @JsonProperty("dataSize") private int dataSize; public List<Item> getItemList() { return itemList; } public void setItemList(List<Item> itemList) { this.itemList = itemList; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getDataSize() { return dataSize; } public void setDataSize(int dataSize) { this.dataSize = dataSize; } } // Model for each item in dataList public class Item { @JsonProperty("itemCode") private String itemCode; @JsonProperty("itemTypeKey") private String itemTypeKey; @JsonProperty("itemCategoryKey") private String itemCategoryKey; @JsonProperty("itemSubCategoryKey") private String itemSubCategoryKey; @JsonProperty("itemName") private String itemName; @JsonProperty("displayName") private String displayName; // Getters and setters for all fields public String getItemCode() { return itemCode; } public void setItemCode(String itemCode) { this.itemCode = itemCode; } public String getItemTypeKey() { return itemTypeKey; } public void setItemTypeKey(String itemTypeKey) { this.itemTypeKey = itemTypeKey; } public String getItemCategoryKey() { return itemCategoryKey; } public void setItemCategoryKey(String itemCategoryKey) { this.itemCategoryKey = itemCategoryKey; } public String getItemSubCategoryKey() { return itemSubCategoryKey; } public void setItemSubCategoryKey(String itemSubCategoryKey) { this.itemSubCategoryKey = itemSubCategoryKey; } public String getItemName() { return itemName; } public void setItemName(String itemName) { this.itemName = itemName; } public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } }
Then deserialize the JSON:
import com.fasterxml.jackson.databind.ObjectMapper; public class JsonToModelExample { public static void main(String[] args) throws Exception { // Your full JSON response string String jsonResponse = "{ \"data\":{ \"dataList\":[{ \"itemCode\":\"item-49861\", \"itemTypeKey\":\"drugs\", \"itemCategoryKey\":\"general\", \"itemSubCategoryKey\":\"fever and pain\", \"itemName\":\"Combiflam\", \"displayName\":\"Combiflam tablet 250mg\" }, { \"itemCode\":\"item-298611\", \"itemTypeKey\":\"drugs\", \"itemCategoryKey\":\"general\", \"itemSubCategoryKey\":\"fever and pain\", \"itemName\":\"Crocin\", \"displayName\":\"Crocin tablet 250mg\" }], \"pageSize\":2, \"dataSize\":2 } }"; ObjectMapper objectMapper = new ObjectMapper(); ItemResponse response = objectMapper.readValue(jsonResponse, ItemResponse.class); // Access the data System.out.println("Total items: " + response.getData().getDataSize()); response.getData().getItemList().forEach(item -> System.out.println("Item: " + item.getDisplayName()) ); } }
Kotlin (Using Data Classes & Jackson)
Kotlin’s data classes make model definition way more concise. Here’s the implementation:
import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.kotlin.registerKotlinModule // Top-level response data class data class ItemResponse( @JsonProperty("data") val data: ItemData ) // Inner data class for the "data" field data class ItemData( @JsonProperty("dataList") val itemList: List<Item>, @JsonProperty("pageSize") val pageSize: Int, @JsonProperty("dataSize") val dataSize: Int ) // Data class for each item in dataList data class Item( @JsonProperty("itemCode") val itemCode: String, @JsonProperty("itemTypeKey") val itemTypeKey: String, @JsonProperty("itemCategoryKey") val itemCategoryKey: String, @JsonProperty("itemSubCategoryKey") val itemSubCategoryKey: String, @JsonProperty("itemName") val itemName: String, @JsonProperty("displayName") val displayName: String ) // Deserialization code fun main() { val jsonResponse = "{ \"data\":{ \"dataList\":[{ \"itemCode\":\"item-49861\", \"itemTypeKey\":\"drugs\", \"itemCategoryKey\":\"general\", \"itemSubCategoryKey\":\"fever and pain\", \"itemName\":\"Combiflam\", \"displayName\":\"Combiflam tablet 250mg\" }, { \"itemCode\":\"item-298611\", \"itemTypeKey\":\"drugs\", \"itemCategoryKey\":\"general\", \"itemSubCategoryKey\":\"fever and pain\", \"itemName\":\"Crocin\", \"displayName\":\"Crocin tablet 250mg\" }], \"pageSize\":2, \"dataSize\":2 } }" val objectMapper = ObjectMapper().registerKotlinModule() val response = objectMapper.readValue(jsonResponse, ItemResponse::class.java) println("Total items: ${response.data.dataSize}") response.data.itemList.forEach { println("Item: ${it.displayName}") } }
Python (Using Pydantic)
Pydantic is the standard for data validation and serialization in Python. Here’s how to model your response:
from pydantic import BaseModel from typing import List # Model for each item in dataList class Item(BaseModel): itemCode: str itemTypeKey: str itemCategoryKey: str itemSubCategoryKey: str itemName: str displayName: str # Model for the inner "data" object class ItemData(BaseModel): dataList: List[Item] pageSize: int dataSize: int # Top-level response model class ItemResponse(BaseModel): data: ItemData # Deserialization code if __name__ == "__main__": json_response = """{ "data":{ "dataList":[{ "itemCode":"item-49861", "itemTypeKey":"drugs", "itemCategoryKey":"general", "itemSubCategoryKey":"fever and pain", "itemName":"Combiflam", "displayName":"Combiflam tablet 250mg" }, { "itemCode":"item-298611", "itemTypeKey":"drugs", "itemCategoryKey":"general", "itemSubCategoryKey":"fever and pain", "itemName":"Crocin", "displayName":"Crocin tablet 250mg" }], "pageSize":2, "dataSize":2 } }""" response = ItemResponse.model_validate_json(json_response) print(f"Total items: {response.data.dataSize}") for item in response.data.dataList: print(f"Item: {item.displayName}")
Key Notes
- Field Matching: Ensure your model field names exactly match the JSON keys, or use annotations (like
@JsonPropertyin Java/Kotlin) to map different code names to JSON keys. - Optional Fields: If some JSON fields might be missing, mark them as nullable in your models (e.g.,
String?in Kotlin,Optional<String>in Java,Optional[str]in Pydantic). - Libraries: Always use a well-maintained serialization library for your language—they handle edge cases like nested objects, arrays, and type conversion automatically.
内容的提问来源于stack exchange,提问作者Prabal.PX

