英文:
POJO class from JSON with a value that can either be string on integer
问题
我有一个JSON文件,其中有一个名为"code"的值,可以是字符串也可以是整数。
{
"code": 110005,
"name": "abcd"
},
{
"code": "090270",
"name": "efgh"
}
我该如何创建一个与之对应的POJO类?
期望的输出是字符串。
英文:
I have a JSON file with a value "code" that can either be a string or an integer.
{
"code": 110005,
"name": "abcd"
},
{
"code": "090270",
"name": "efgh"
}
How do I create a POJO class with this?
Expected Output is string
答案1
得分: 0
只需使用String创建POJO。无论您为字段提供的值是String还是整数,代码中都将视为String。
英文:
Just create POJO with String. Whatever the value you provide for the fields, a String or integer, it would be considered as String in code.
答案2
得分: 0
你可以将包含数字的字段转换为字符串:
const data = [{
"code": 110005,
"name": "abcd"
},
{
"code": "090270",
"name": "efgh"
}
]
console.log(createObj(data))
function createObj(data) {
return data.map(entry => {
return {
code: entry.code.toString(),
name: entry.name
}
})
}
英文:
You can cast the fields that contain numbers to strings:
const data = [{
"code": 110005,
"name": "abcd"
},
{
"code": "090270",
"name": "efgh"
}
]
console.log(createObj(data))
function createObj(data) {
return data.map(entry => {
return {
code: entry.code.toString(),
name: entry.name
}
})
}
专注分享java语言的经验与见解,让所有开发者获益!
评论