C#中是否存在http响应解析器?

时间:2013-05-06 23:06:59

标签: c# html json httpwebrequest response

{"sentences":[{"trans":"událost","orig":"event","translit":"","src_translit":""}],"dict":[{"pos":"podstatné jméno","terms":["událost","případ","příhoda","soutěž","sportovní disciplína"],"entry":[{"word":"událost","reverse_translation":["event","occurrence","incident","happening","affair"],"score":0.6872893},{"word":"případ","reverse_translation":["CASE","event","instance","occurrence","episode","subject"],"score":0.017476905},{"word":"příhoda","reverse_translation":["event","incident","episode"],"score":0.0021874912},{"word":"soutěž","reverse_translation":["competition","contest","event"],"score":0.0017304479},{"word":"sportovní disciplína","reverse_translation":["event"],"score":3.2700344e-05}]}],"src":"en","server_time":45}

这段代码我需要解析自己的对象(这是谷歌翻译响应)。 .NET中是否存在“http响应解析器助手”?

像这样的东西(谷歌浏览器)。

enter image description here

4 个答案:

答案 0 :(得分:4)

那是JSON数据。 Json.NET是一个很好的用于.NET的JSON(de)序列化程序。

答案 1 :(得分:1)

那是JSON。使用任何C#JSON反序列化器。

答案 2 :(得分:1)

查看System.Runtime.Serialization.Json.DataContractJsonSerializer类,它内置于.Net。

http://msdn.microsoft.com/en-us/library/bb412179.aspx

答案 3 :(得分:1)

这是Json,您可以使用任何json-parser解析它。我将使用Json.Net并使用dynamic关键字

这是您要解析的json

enter image description here

dynamic json  = JsonConvert.DeserializeObject(text);

foreach (var sentence in json.sentences)
{
    Console.WriteLine((string)sentence.trans);
}
Console.WriteLine();


foreach (var d in json.dict)
{
    Console.WriteLine("***TERMS***");
    foreach (var term in d.terms)
    {
        Console.WriteLine((string)term);
    }

    Console.WriteLine("***ENTRY***");
    foreach (var entry in d.entry)
    {
        Console.WriteLine((string)entry.word + " , "  + (double)entry.score);
    }
}

您还可以使用this site将json反序列化为类型安全的类。代码是

var jObj = JsonConvert.DeserializeObject<RootObject>(text);


public class Sentence
{
    public string trans { get; set; }
    public string orig { get; set; }
    public string translit { get; set; }
    public string src_translit { get; set; }
}

public class Entry
{
    public string word { get; set; }
    public List<string> reverse_translation { get; set; }
    public double score { get; set; }
}

public class Dict
{
    public string pos { get; set; }
    public List<string> terms { get; set; }
    public List<Entry> entry { get; set; }
}

public class RootObject
{
    public List<Sentence> sentences { get; set; }
    public List<Dict> dict { get; set; }
    public string src { get; set; }
    public int server_time { get; set; }
}