POJO类从JSON中提取一个可以是字符串或整数的值。

huangapple 未分类评论52阅读模式
英文:

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
    }
  })
}

huangapple
  • 本文由 发表于 2020年5月30日 04:00:13
  • 转载请务必保留本文链接:https://java.coder-hub.com/62093792.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定