【发布时间】:2017-04-21 03:09:06
【问题描述】:
我一直在阅读有关此问题的大量问题,但似乎无法解决我的特定问题。
我正在从 Web 服务函数返回一个 json 字符串。
我有这些物品:
public class WebServiceInitResult
{
public List<Activity> Activities { get; set; }
//rest of properties left out...
}
public class Activity
{
public string IconCode { get; set; }
//rest of properties left out...
}
IconCode 是字体真棒字符的字符代码,以下任意一个:
\uf0b1
\uf274
\uf185
\uf0fa
\uf0f4
\uf015
它们完全如上所示存储在数据库中。
当我像下面这样设置httpReponse.Content 时,反斜杠被转义:
httpResponseMessage.Content = new StringContent(JsonConvert.SerializeObject(webServiceInitResult), Encoding.UTF8, "application/json");
PostMan收到的json响应是:
"activities": [
{
"ActivityCode": 2,
"DisplayValue": "Shopping",
"BackgroundColour": "E74C3C",
"IconCode": "\\uf0b1",
"ApplicationId": 2,
"Application": null,
"Id": 1,
"Active": true,
"DateCreated": "2016-11-25T10:15:40"
},
//rest of activities
]
如您所见,IconCode 反斜杠已被转义。通过阅读其他问题,我无法自信地确定 Json.NET 在序列化或发送响应时是否会发生这种情况。
我尝试使用 ObjectContent 来解决问题,这样我可以避免使用 Json.NET,但它返回了相同的结果!
httpResponseMessage.Content = new ObjectContent(typeof(TravelTrackerWebServiceInitResult), webServiceInitResult, new JsonMediaTypeFormatter() , "application/json");
现在我被卡住了!
有没有更好的方法可以返回我需要的东西?应用程序使用这些字符来显示相应的图标。
额外信息: 我最初对这些值进行了硬编码,一切似乎都正常:
webServiceInitResult.activities_TT = new List<Activity_TT>()
{
new Activity() { ActivityCode = 2, BackgroundColour = "E74C3C", DisplayValue="Shopping", IconCode="\uf0b1" },
new Activity() { ActivityCode = 3, BackgroundColour = "BF7AC5", DisplayValue="Running", IconCode="\uf274" },
new Activity() { ActivityCode = 4, BackgroundColour = "AF7AC5", DisplayValue="Walking", IconCode="\uf185" },
new Activity() { ActivityCode = 5, BackgroundColour = "3498DB", DisplayValue="Jogging", IconCode="\uf0fa" },
new Activity() { ActivityCode = 6, BackgroundColour = "2ECC71", DisplayValue="Resting", IconCode="\uf0f4" },
new Activity() { ActivityCode = 7, BackgroundColour = "F39C12", DisplayValue="Skipping", IconCode="\uf015" }
};
谢谢。
【问题讨论】:
-
"IconCode 是一个 fontawesome 字符的字符代码,其中任何一个:
\uf0b1\uf274\uf185\uf0fa\uf0f4\uf015它们存储在一个完全如上所示的数据库。” 那么这就是问题所在。如果它们被存储为字符`,u,f,0,b,1, then the JSON serializer is doing exactly the right thing by escaping that backslash. If you want that unicode escape processed, you need to process it before assigning it to yourIconCode`字符串,那么字符串实际上包含字符,而不是其unicode转义的字符串. -
如何设置
IconCode变量?如果您使用 C# 文字,您会得到实际的 Unicode 字符,not 您发布的内容。Debug.Assert("\uf0b1".Length ==1) -
数据库也没有 Unicode 问题,您可以将任何内容存储在
nvarchar列中。如果您将转义序列存储为 6 个单独的字符,而不是实际字符,您的代码 应该首先取消转义。为什么不将值存储在 Unicode 列中? -
该字符串被第三方使用,他们特别请求格式为 \uf0b1 的数据。如何将其存储在数据库中并以这种格式返回给第三方。
-
@T.J.Crowder 那么我将如何处理它?我不确定你的意思。
标签: c# json web-services json.net