NewtonSoft.JSON反序列化无法正常工作

时间:2013-12-13 12:31:15

标签: c# json json.net

我有以下JSON字符串:

{
  [    
    {
        "error": {
                     "typeofdevice": 678,
                     "valueconvert": "",
                     "message": "oops something went wrong"
                 }
    }
  ]
}

对此进行反序列化并获取“消息”的值的最佳方法是什么?

我试过了:

JToken token = JArray.Parse(args.Result);
string message = (string)token["description"];

然后它说

  

数组缺少一个索引,它无效。

我知道的新人问题..但我无法弄明白:S。

Grtz。

2 个答案:

答案 0 :(得分:1)

using System;
using System.Collections.Generic;

namespace ConsoleApplication2
{
    using Newtonsoft.Json;

    internal class Program
    {
        private static void Main(string[] args)
        {
            string jsonString =
                "["
                + "{"
                + " \"error\": "
                + "     {" 
                + "         \"typeofdevice\": 678,"
                + "         \"valueconvert\": \"\"," 
                + "         \"message\": \"oops something went wrong\"" 
                + "     }" 
                + "}" 
              + "]";

            List<Data> data = JsonConvert.DeserializeObject<List<Data>>(jsonString);
            Console.WriteLine(data[0].Error.typeofdevice);
        }

        public class Data
        {
            public Error Error { get; set; }
        }

        public class Error
        {

            public string typeofdevice { get; set; }
            public string valueconvert { get; set; }
            public string message { get; set; }
        }
    }
}

上面的控制台应用程序有效,但我已经更改了你的JSON字符串,因为其他人正确地指出它是无效的JSON。

答案 1 :(得分:0)

此外,如果您想检查JSON数据是否正确,可以在此处发送数据:

http://jsoneditoronline.org/index.html

相关问题