[英]Serialize to JSON in C# and deserialize in TS
我在两个应用程序之间发送数据时遇到问题。 我使用以下代码在 C# 中将数据序列化为 JSON:
public static string SerializeToJson<T>(this T obj)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, obj);
byte[] array = ms.ToArray();
return Encoding.UTF8.GetString(array, 0, array.Length);
}
然后我使用套接字通信将其发送到我在 TypeScript 中实现的第二个应用程序。 我反序列化它使用:
JSON.parse
函数并且它工作正常,但是如果数据中是特殊字符,例如 8211 '-' 它会抛出异常
SyntaxError: Unexpected token in JSON at position 907
也许是序列化和反序列化不同编码的问题,但我不知道在 JSON.parse 中使用哪种编码。
任何人都可以帮助我吗?
另一种方法是使用Newtonsoft Json.Net (可从 nuget 获得)。 它易于使用且非常强大。
public static string SerializeToJson<T>(this T obj)
{
return JsonConvert.SerializeObject(obj);
}
您甚至可以添加一些格式或您想要的内容。
我使用将字符串转换为 base64 来解决这个问题,然后在我的第二个应用程序中对其进行解码。
以下代码对我有用。 以下解决方案还确保了底层对象的类型。 将C# 对象转换为 typescript 对象。
使用任何 JSON 库将您的对象转换为 json 格式。 (newtonsoft 是最推荐的一款)
string output = JsonConvert.SerializeObject(product); // product =new Product(); <= Product is custom class. substitute your class here
将此字符串传递给您的应用程序。 (ActionResult 或 ajax 调用)
现在在 javascript 中使用模型访问值(Razor 或 ajax 结果)
YourTSClass.ProcessResults('@Model') // using razor in js
或者
.done(response => {ProcessResults(response)}) // using ajax success result
您不需要以这种方式应用 JSON.Parse。
在打字稿中,您可以通过像这样声明函数来获得结果。
public static ProcessResults(result: Product){...}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.