C#反序列化动态JSON [英] C# deserialize dynamic JSON

查看:139
本文介绍了C#反序列化动态JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要反序列化以下Json字符串.

I have the following Json string that I need to deserialize.

{"123456789":
  {"short_description":"Delivered",
     "detail_description":"Your item has been delivered"
   }
}

第一个字段"123456789"是一个ID号,因此基本上这个值可以根据要查询的数据而有所不同.

The first field "123456789" is an id number, so basically this value can be different depending on the data being queried.

我在Visual Studio中使用C#.显然,因为第一个字段的值可以更改,所以我不能使用预定义的类将JSON反序列化为该字段,因为该字段将用作类名,但该字段的值与该类名不匹配.

I'm using C# in visual studio. Obviously because the value of the first field can change I can't use a predefined class to deserialize the JSON into because this field will be used as the class name but the field value won't match the class name.

是否有一种方法可以将其反序列化为某种动态类,但仍可以像访问预定义类一样访问字段?

Is there a way to deserialize this into some sort of dynamic class but still access the fields as if it was a predefined class?

或者,即使认为类名不匹配,也可以将其反序列化为预定义的类吗?

Alternatively is there a way to deserialize this into a predefined class even thought the class name doesn't match?

提供此数据的服务是第三方的,因此我对此没有任何控制.

The service providing this data is a third party one so i don't have any control over it.

推荐答案

这是我在生产代码中使用的一种方法.它可能并不完美,但是可以完成工作.

Here is one way which I use in production code. It might not be perfect, but it gets the job done.

using using System.Web.Script.Serialization;

// .....

    public object GetJson(string url)
    {
        var json = Get(url); // I have code that makes this work, it gets a JSON string

        try
        {
            var deserializer = new JavaScriptSerializer();
            var result = deserializer.DeserializeObject(json);

            return result;
        }
        catch (ArgumentException e)
        {
            // Error handling....
        }            
    }

您收到的对象将是通用Map,List或其他取决于JSON结构的对象.如果您知道期望的结构,那么无需编写自定义的解析器或目标对象类型,这将非常有用.

The object you receive back will be a generic Map, List, or whatever depending on the structure of the JSON. If you know what structure to expect, this is very useful without writing a customized parser or target object type.

然后,您可以枚举Map的键,例如,找到变化的键.然后,包装程序或转换程序将为其余的应用程序层提供一致的API.像这样:

You could then enumerate the keys of the Map, for example, to find your key that varies. A wrapper or conversion would then provide a consistent API to the rest of your application layer. Something like:

public class Order {
     public string OrderNum { private set; get; }
     public string ShortDesc { private set; get; }
     public string Desc { private set; get; }

     public static Order FromJson(object jsonResult) 
     {
          var m = jsonResult as Map<string, object>;

          // Handle errors, but I am not

          var firstPair = m.First();

          var detail = firstPair.Value as Map<string, object>;

          var dummy = new Order()
          {
              OrderNum = firstPair.Key,
              ShortDesc = detail["short_description"].ToString();
              Desc = detail["detail_description"].ToString();
          }

          return dummy;
     }
}

这篇关于C#反序列化动态JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆