如何在客户端将Json数据设置为camelCase
本文关键字:数据 设置 camelCase Json 客户端 | 更新日期: 2023-09-27 18:03:34
如何将序列化的json数据转换为camelCase数据而不是所有属性都大写?
在我的视图中,这是我如何在Json中转换c#
team = @Html.Raw(Json.Encode(Model.Employees));
这是数据:"所有这些都是测试数据"
team = [
{
"UserId": "902c2fe0-fcdf-4ed8-9591-5d8e01300cda",
"UserName": "buderbits",
"ID": 719,
"Email": "erik@builder.com",
"FName": "Builder",
"LName": "Bits",
"Title": "Glaizer",
"Zip": "10027",
"Phone": "456-768-9987",
"AddressLine": "124 street st.",
"City": "Nyc",
"StateCD": "NY",
"Avatar": "/users/RFyEQxDCpEavRfgDA028/qvzlezay.u1l.png",
"RowNum": 3,
"Total": 4,
"IsDirty": false,
"IsFlaggedForDelete": false,
"SortOrder": 0
},
{
"UserId": "a9cec535-ac48-4197-b8a0-87702cb14e52",
"UserName": "stdard",
"ID": 717,
"Email": "erik@vinyl.org",
"FName": "Erik",
"LName": "Little",
"Title": "Developer",
"Zip": "75040",
"Phone": "123-456-7890",
"AddressLine": "123 Test Street",
"City": "Garland",
"StateCD": "TX",
"Avatar": "/users/CZmP9uvdTCg8CdEhOAX0/kcm1yg2o.spn.gif",
"RowNum": 1,
"Total": 4,
"IsDirty": false,
"IsFlaggedForDelete": false,
"SortOrder": 0
},
{
"UserId": "1a4ef17a-9cd8-42e4-b172-3071e29a222a",
"UserName": "teammber1",
"ID": 2744,
"Email": "erik2@erik.com",
"FName": "Derick",
"LName": "Mavrick",
"Title": "Drafting",
"Zip": "77702",
"Phone": "111-111-1111",
"AddressLine": "123 Teammember ST",
"City": "Beaumont",
"StateCD": "TX",
"Avatar": "/users/rPF9z0a7yLJpp4e1Zb15/os1cmk0r.kkg.jpg",
"RowNum": 4,
"Total": 4,
"IsDirty": false,
"IsFlaggedForDelete": false,
"SortOrder": 0
},
{
"UserId": "17fab37f-d978-441c-a30d-8c08a7e6ce9b",
"UserName": "stoontsoftware",
"ID": 718,
"Email": "support@storefront.net",
"FName": "Mark",
"LName": "Taylor",
"Title": "Hosting",
"Zip": "75070",
"Phone": "345-432-1153",
"AddressLine": "123 street dr",
"City": "McKinney",
"StateCD": "TX",
"Avatar": "/users/y5TPPr0HR1GQLxkEhDuj/3bmwy0sk.qoi.png",
"RowNum": 2,
"Total": 4,
"IsDirty": false,
"IsFlaggedForDelete": false,
"SortOrder": 0
}
];
帮助吗?
你可以使用Newtonsoft的json序列化器(Json.net),它允许你在序列化对象时指定格式化器。
var d = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model.Employees,
new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
}));
console.log(d);
这将为序列化创建的js对象/数组提供小写的属性名。
您可以在发送到客户端之前将字段转换为驼峰大小写,方法是将初始查询转换为带有驼峰大小写字段的动态对象或视图模型。例如,如果原始查询:
var model=db.Records.ToList();
生成您的输出,然后将查询修改为:
var model=db.Records.Select(r=>
new {firstName=r.FirstName,lastName=LastName, etc...).ToList();
要在客户端真正做到100%,您需要使用javascript方法重新构建您的表对象,该方法将每个对象替换为正确命名的对象。
function NewObject(input){
input=input||{};
this.firstName=input.FirstName||'';
this.lastName=input.LastName||'';
...etc.
}
var model=@Model; //your Json data as an object
for(var i=0;i<model.length;i++){
model[i]=new NewObject(model[i]);
}