json - 格式化 SPA 使用的 JSON 数据的最佳方法是什么?
问题描述
我正在与一位朋友一起开发单页应用程序(在 React 中,但我相信框架并不重要,同样的问题也适用于 Angular)。
有一个包含 2 个表的数据库:
- 特征
- 车
两个表在数据库中以多对多关系连接。
我们的不同之处在于我们应该如何将数据从后端传递到前端(更准确地说,CarManagementComponent 将让用户处理汽车/功能(编辑/更新/删除等))。我们希望能够在之前执行多个操作,实际上是向后端发送请求以更新数据库,以便用户拥有类似桌面应用程序的界面体验。
请记住,数据库中有更多表,但为了示例的简单性,我们在这里只讨论其中的 2 个。
1)我的方法:
{
"Features": [
{
"Id": 0,
"Price": 3000,
"Name": "led lights",
"Color": "transparent",
"Brand": "Valeo",
"Guarantee": 12
},
{
"Id": 1,
"Price": 1000,
"Name": "air conditioning",
"Color": "",
"Brand": "Bosch",
"Guarantee": 12
},
{
"Id": 2,
"Price": 600,
"Name": "tinted windows",
"Color": "",
"Brand": "Bosch",
"Guarantee": 36
}
],
"Cars": [
{
"Id": 0,
"Name": "Ford Mustang GT",
"Weight": 2210,
"Features":[
{
"Id": 0, // id of many-to-many relations record
"FeatureId": 2
},
{
"Id": 1, // id of many-to-many relations record
"FeatureId": 1
}
]
},
{
"Id": 1,
"Name": "Volkswagen Arteon",
"Weight": 1650,
"Features":[
{
"Id": 2, // id of many-to-many relations record
"FeatureId": 2
}
]
}
]
}
2)我朋友的做法:
{
"Cars": [
{
"Id": 0,
"Name": "Ford Mustang GT",
"Weight": 2210,
"Features": [
{
"Id": 1,
"Price": 1000,
"Name": "air conditioning",
"Color": "",
"Brand": "Bosch",
"Guarantee": 12
},
{
"Id": 2,
"Price": 600,
"Name": "tinted windows",
"Color": "",
"Brand": "Bosch",
"Guarantee": 36
}
]
},
{
"Id": 1,
"Name": "Volkswagen Arteon",
"Weight": 1650,
"Features": [
{
"Id": 2,
"Price": 600,
"Name": "tinted windows",
"Color": "",
"Brand": "Bosch",
"Guarantee": 36
}
]
}
]
}
我相信第一种方法更好,因为:
- 重量更轻(无数据冗余)
- 将此类数据转换为面向对象的结构会更容易
- 例如。我们能够看到所有功能记录(在第二种方法中,我们只会看到与 Cars 连接的记录,并且需要另一个后端请求)
- 例如。与第二种方法不同,我们能够在 1 个请求中获得所有需要的数据(同步问题更少),我们也可以在单个请求中保存修改后的数据
我的朋友说第二种方法更好,因为:
- 使用 ORM (hibernate) 会更容易实现
- 他一生中从未见过第一种方法(这可能会得出结论,它是以错误的方式完成的)
你怎么看?哪种解决方案更好?也许他们都在某些领域?也许我们还没有想到第三种解决方案?
解决方案
我想说我最喜欢的方法是你的,主要原因有两个:
- 请记住,HTTP 请求中的数据重复很糟糕,您的方法是避免它。
- 您让
FeatureId
汽车内部成为对象,并且足以以有效的性能 O(N) 获得该功能。
为了使它更好,您可以将您的功能结构更改为:
"Features": {
0: { // <- If the id is unique, you can use it as a key.
"Id": 0,
"Price": 3000,
"Name": "led lights",
"Color": "transparent",
"Brand": "Valeo",
"Guarantee": 12
},
1: {
"Id": 1,
"Price": 1000,
"Name": "air conditioning",
"Color": "",
"Brand": "Bosch",
"Guarantee": 12
},
2: {
"Id": 2,
"Price": 600,
"Name": "tinted windows",
"Color": "",
"Brand": "Bosch",
"Guarantee": 36
}
},
这样,您可以获得 O(1) 中的特征。
推荐阅读
- c# - 为什么我可以检查 Struct 是否等于 null?
- scala - 如何在 spark sql(Scala) 中解析 url
- android - 将 View 放在 TabLayout 下面的 ViewPager 中
- validation - 微服务:如何从其他微服务进行验证
- javascript - Visual Studio 中的注释行(单行和多行)
- scala - 在 Akka Http 中返回一个 JSON 数组
- php - Laravel 使用 Sum 和 Groupby
- elasticsearch - Kibana WAU 条形图
- json - 在智能手机上运行 Ionic Framework 应用程序时不会加载静态 .json 文件
- python - 为什么 sqlalchemy 忽略 load_only?