我面临着一个相当讨厌的问题,但却无法在互联网上找到一个好的解决方案。我有一个Android应用程序,可以下载一个包含有关用户信息的大型JSON对象。格式如下:
{
"dateOfBirth": {
"day": 25,
"month": 3
},
"educations": {
"_total": 1,
"values": [{
"activities": "Music Society, Rugby college team",
"degree": "BA Computer Science",
"endDate": {"year": 2015},
"fieldOfStudy": "Computer Science",
"id": 298659638,
"notes": "The courses I enjoyed most are: Object-Oriented Programming, Data Structures and Algorithms, Compilers, Databases, Computer Networks and Computer Security.",
"schoolName": "University of Oxford",
"startDate": {"year": 2012}
}]
},
"firstName": "Roland",
"id": "-1QlZwe5fx",
"languages": {
"_total": 2,
"values": [
{
"id": 1,
"language": {"name": "English"}
},
{
"id": 2,
"language": {"name": "Romanian"}
}
]
},
"lastName": "Batovski",
"location": {"country": {"code": "gb"}}
...
}
我必须发送此数据的服务器具有它期望的特定JSON格式,即它希望数据采用以下格式:
{
"userid": "Yohv74kuNm",
"profile": [],
"goalData": [
"Founders",
"Travel"
],
"event": "1",
"pin": "",
"_id": "c9lZlvo9SEcIwDBR",
"person": {
"id": {
"text": "Yohv74kuNm"
},
"languages": {
"total": "2",
"language": [
{
"id": {
"text": "57739336"
},
"language": {
"name": {
"text": "English"
}
}
}
]
},
"skills": {
"total": "15",
"skill": [
{
"id": {
"text": "11"
},
"skill": {
"name": {
"text": "Start-ups"
}
}
},
{
"id": {
"text": "13"
},
"skill": {
"name": {
"text": "Entrepreneurship"
}
}
},
... }
显然,这些对象完全不同,但基本上它们拥有相同的数据。我正在寻找一种方法来轻松地将一个映射到另一个。从我收到的数据中获取数据,并创建一个我填写的新JSON对象。请记住,这些对象相当大并且有很多嵌套值。我尝试使用JavaEE的JsonObjectBuilder,但创建了一个大小似乎很多手动工作的对象(我在下面快速尝试)。
JsonObject jsonString = factory.createObjectBuilder()
// add the fields here
.add("id", factory.createObjectBuilder()
.add("text", this.jsonObject.get("id").getAsString())
.build())
.add("languages", factory.createObjectBuilder()
.add("total", this.jsonObject.get("languages").getAsJsonObject().get("_total").getAsString())
.build())
.build()
感谢您的帮助!
答案 0 :(得分:0)
我会做什么:
另一种可能性是让你的java对象反映两个json结构中的一个,并使用custom serializer来处理另一个json结构。