【问题标题】:NewtonSoft.JSON deserializing not workingNewtonSoft.JSON 反序列化不起作用
【发布时间】:2013-12-13 12:31:14
【问题描述】:

我有以下JSON 字符串:

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

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

我试过了:

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

然后它说

数组缺少索引,并且它不工作。

菜鸟问题我知道..但我想不通:S.

Grtz。

【问题讨论】:

  • 为什么不呢?这是一个官方 API,所以我想它应该可以正常工作,因为它适用于很多其他人。
  • 试试jsonlint.com

标签: c# json json.net


【解决方案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。

【讨论】:

    【解决方案2】:

    另外,如果你想检查你的JSON数据是否正确,你可以在这里发送你的数据:

    http://jsoneditoronline.org/index.html

    【讨论】:

      猜你喜欢
      • 2014-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-02
      • 2020-06-07
      • 1970-01-01
      相关资源
      最近更新 更多