简体   繁体   中英

Serialize to JSON in C# and deserialize in TS

I have problem with send data between my two apps. I serialize data to JSON in C# using this code:

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);
}

and then i send this using socket communication to my second application which is implemented in TypeScript. I deserialize it using:

JSON.parse

function and it works fine, but if in data is special characters for example 8211 '–' it throw exception

SyntaxError: Unexpected token  in JSON at position 907

Maybe it is problem with different encoding with serialize and deserialize, but I don't know which encoding is used in JSON.parse.

Anyone can help me?

An alternative is to use Newtonsoft Json.Net (available from nuget). It's easy to use and very powerfull.

public static string SerializeToJson<T>(this T obj)
{
    return JsonConvert.SerializeObject(obj);
}

And you can even add some formating or what you want.

我使用将字符串转换为 base64 来解决这个问题,然后在我的第二个应用程序中对其进行解码。

The following code worked for me. The following solution also ensures the type of underlying objects. To Convert C# object to typescript object .

Convert your object to json format using any of the JSON libraries. (newtonsoft is most suggested one)

string output = JsonConvert.SerializeObject(product); // product =new Product(); <= Product is custom class. substitute your class here

Pass this string to your application. (ActionResult or ajax call)

Now in the javascript access the value using Model (Razor or ajax result)

YourTSClass.ProcessResults('@Model') // using razor in js

or

 .done(response => {ProcessResults(response)}) // using ajax success result

You need not apply JSON.Parse this way.

In the typescript you can get the result by declaring the function like this.

public static ProcessResults(result: Product){...}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM