创建一个动态映射,用于将多个输入文件解析为kotlin中的obj



假设我有一个json数据,它可以对同一数据字段具有不同的密钥名称

Json A型

{"宽度":1024,"高度":768,"color":"#ff0000"}

还有一个映射json,它为我提供了应该用数据类中的内容映射的attirbuteJson A型

{"宽度":w,"高度":h,"color":"color"}

Json Type B

{"widthOfobj":1024,"物体高度":768,"colorOfobj":"#ff0000"}

Json类型映射文档B

{"widthOfobj":w,"heightOfobj":h,"colorOfobj":"颜色"}

在我的kotlin数据类中,我将obj定义为

data class dimension(W: int, H: int, Color: String)

现在,我想在阅读映射文档的帮助下,将json类型A或B映射到kotlin数据类。我该怎么做这样的事?

以下是我为清晰起见所考虑的流程

sudo代码

Data class dimension( W: int, H: int, Color:String)// already defined
//Read mapping document to map 
val Map = readmappingfile(mappingfile)  //e. g  Width to W
//      Height to H
Val input Data= readJson(input) //      { "width": 1024, "height": 768, "color": "#ff0000" }
Val show result = applytransformation( mappingfile, input)
// inside applytransformation Read the Map and data and serialize it to data class  
//oneway of just serializing  it would be using gson 
val result = gson.fromJson(input,dimension::class.java) // this would work if input was in format ( w->v , h-> v , Color->v) 

//在调用上面的gson代码将其序列化为数据类之前,我如何进行更改以将权重转换为W。请注意,它需要足够动态,这样我们就不会编写硬编码映射。

我认为您应该为gson使用自定义反序列化程序。

看看这个例子。

最新更新