Parsing the JSON with multilingual text using Syst

2019-09-11 03:41发布

问题:

I had asked this question before. The solution using Newtonsoft worked great until I deployed the website on web hosting server, where its giving me nightmares. Therefore, I am planning to use some System.Web libraries so that I don't have to deal with *.dlls and such and I can easily deploy my website.

Can someone help me parse the same json output using System.Web.Script.Serialization or any System library? Thanks a lot.

回答1:

I hope your real json string is valid since the one you posted is corrupted but Json.Net tolerates it.

The only trick is deserializing to this funny type List<Dictionary<string,object>>

Here is an example with corrected json(removed trailing ,s)

string json = @"[ { ""ew"" : ""bharat"", ""hws"" : [ ""\u092D\u093E\u0930\u0924"",""\u092D\u0930\u0924"",""\u092D\u0930\u093E\u0924"",""\u092D\u093E\u0930\u093E\u0924"",""\u092C\u0939\u0930\u0924"" ] }, { ""ew"" : ""india"", ""hws"" : [ ""\u0907\u0902\u0921\u093F\u092F\u093E"",""\u0907\u0928\u094D\u0921\u093F\u092F\u093E"",""\u0907\u0923\u094D\u0921\u093F\u092F\u093E"",""\u0908\u0928\u094D\u0921\u093F\u092F\u093E"",""\u0907\u0928\u0921\u093F\u092F\u093E"" ] } ]";
var list = new JavaScriptSerializer().Deserialize<List<Dictionary<string,object>>>(json);

foreach (var dict in list)
{
    var ew  = (string)dict["ew"];
    var firstValOfHws = ((ArrayList)dict["hws"])[0];
}

--EDIT--

OK, This should work

var serializer = new DataContractJsonSerializer(typeof(List<Result>));
var result = (List<Result>)serializer.ReadObject(new MemoryStream(Encoding.UTF8.GetBytes(json)));

public class Result
{
    public string ew;
    public List<string> hws;
}