简体   繁体   English

C#中的动态对象到JSON

[英]Dynamic object in C# to JSON

I am working with C# and I need to create some JSONs for my application. 我正在使用C#,并且需要为我的应用程序创建一些JSON。 The structure varies and I am not interested in creating a new class to do so. 结构各不相同,我对创建一个新类并不感兴趣。 I'm used to work with javascript objects and ruby dictionaries. 我曾经使用过javascript对象和ruby字典。 I found some suggestions online but none of them worked. 我在网上找到了一些建议,但没有一个起作用。

At the moment, I am working with a JSON object like: 目前,我正在使用JSON对象,例如:

unit: "country",
suggestions: [
    { "value": "United Arab Emirates", "data": "AE" },
    { "value": "United Kingdom",       "data": "UK" },
    { "value": "United States",        "data": "US" }
]

I would like to know if it is possible to create a object where I could easily add and remove objects from suggestions and also manipulate the object like javascript or ruby. 我想知道是否有可能创建一个对象,在这里我可以轻松地从建议中添加和删除对象,以及操纵诸如javascript或ruby之类的对象。

Thanks! 谢谢!

Take a look at Json.NET library. 看一下Json.NET库。 You can deserialize your JSON into dynamic objects: 您可以将JSON反序列化为动态对象:

string json = @"[
  {
    'Title': 'Json.NET is awesome!',
    'Author': {
      'Name': 'James Newton-King',
      'Twitter': '@JamesNK',
      'Picture': '/jamesnk.png'
    },
    'Date': '2013-01-23T19:30:00',
    'BodyHtml': '<h3>Title!</h3>\r\n<p>Content!</p>'
  }
]";

dynamic blogPosts = JArray.Parse(json);
dynamic blogPost = blogPosts[0];
string title = blogPost.Title;
Console.WriteLine(title);
// Json.NET is awesome!

string author = blogPost.Author.Name;

Console.WriteLine(author);
// James Newton-King

DateTime postDate = blogPost.Date;

Console.WriteLine(postDate);
// 23/01/2013 7:30:00 p.m.

Source: http://www.newtonsoft.com/json/help/html/QueryJsonDynamic.htm 资料来源: http : //www.newtonsoft.com/json/help/html/QueryJsonDynamic.htm

I would like to know if it is possible to create a object where I could easily add and remove objects 我想知道是否可以创建一个可以轻松添加和删除对象的对象

Well, i don't understand your requirement completely. 好吧,我不完全理解您的要求。 Are you looking for a dictionary? 您在寻找字典吗?

var dict = new Dictionary<string, object>();
dict.Add("1",new {PropertyA="A",PropertyB="B"});
dict.Add("2", new {SomeotherProp="S"});`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM