C#:JSON嵌套对象反系列化,读取对象的值

//引用命名空间
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;


static void Main(string[] args)
{
    Console.WriteLine("try: ");
	string value = "Hardness France"; //调用百度,返回JSON格式

	string info = TranslationToFra(value);
	//info结果:"{\"from\":\"en\",\"to\":\"fra\",\"trans_result\":[{\"src\":\"Hardness France\",\"dst\":\"la duret\\u00e9 de la france\"}]}\r\n"

	info = info.Replace(":[{", ":{").Replace("}]}", "}}"); //要过滤掉中括号
	ObjectJson model = (ObjectJson)JsonConvert.DeserializeObject<ObjectJson>(info);
	JObject jsonObj = JObject.Parse(info);

	////方法一:
    //string from=jsonObj["from"].ToString();
    //string dst=((JObject )jsonObj["trans_result"])["dst"].ToString();

	//方法二:
    if (!string.IsNullOrWhiteSpace(model.error_code))
    {
        Console.WriteLine(model.error_msg);
    }
    else
    {
        Console.WriteLine(model.trans_result.dst);
    }            

    Console.ReadKey();
}



public class ObjectJson
{
    public string from { get; set; }
    public string to { get; set; }
    public string error_code { get; set; }
    public string error_msg { get; set; }
    public SubObject trans_result { get; set; }
}
public class SubObject
{
    public string src { get; set; }
    public string dst { get; set; }

}

你可能感兴趣的:(C#:JSON嵌套对象反系列化,读取对象的值)