【问题标题】:Deserialize json object xamarin android c#反序列化json对象xamarin android c#
【发布时间】:2016-08-03 12:10:02
【问题描述】:

我对反序列化 json 对象没什么问题。 我的 json 来自 http url:

Screen of my downloaded JSON

我不知道如何反序列化以动态创建按钮。我知道如何使用文本创建按钮,但我不知道如何使用它们拥有的选项来制作它们。我尝试在 Windows 窗体应用程序中获取这些选项进行测试,但应用程序会崩溃。谢谢你的帮助。

【问题讨论】:

    标签: c# json serialization xamarin.android


    【解决方案1】:

    你的类应该是这样的:

    public class Type
    {
        public int id { get; set; }
        public string name { get; set; }
        public bool closedQuestion { get; set; }
        public bool multiAnswer {get; set;}
        public bool usesImage {get; set; }
    }
    public class RootObject
    {
        public int id { get; set; }
        public string name { get; set; }
        public Type type { get; set; }
        public List<string> options { get; set; }
    }
    

    然后您应该能够使用 Newtonsoft.Json 反序列化您的 json:

    List<RootObject> myData = JsonConvert.DeserializeObject<List<RootObject>>(json);
    

    【讨论】:

      【解决方案2】:

      使用Newtonsoft.NET:

      var obj = JsonConvert.DeserializeObject(json);
      

      您还可以创建配对类并使用泛型:

      public JsonClass {
          // Do this for each property you want to map.
          [JsonProperty(PropertyName="id")]
          public int Id { get; set; }
      
          [JsonProperty(PropertyName="name")]
          public int Name { get; set; }
      
          [JsonProperty(PropertyName="type")]
          public MessageType Message { get; set; }
      }
      
      public class MessageType {
          [JsonProperty(PropertyName="id")]
          public int Id { get; set; }
          // etc...
      }
      

      然后做:

      JsonClass obj = JsonConvert.DeserializeObject<JsonClass>(json);
      MessageType messageType = obj.Message;
      

      【讨论】:

      • 太棒了!因此,使用我编写的示例类,将正确的 [JsonProperty(PropertyName="XXX")] 属性放在每个属性上方。 XXX 替换为值的 JSON 名称。所以,对于这个 JSON 字符串:{ name: "Nick", age: "21" },我们会得到这个:[JsonProperty(PropertyName="name")] 上面的 public string Name { get; set; }
      • 实用提示:使用json2csharp.com 从有效的 JSON 字符串中获取 C# 类和属性。只需复制/粘贴,您将获得代码,以便为 JsonConvertDeserialize创建类
      • @NickBull 没问题 :) 使用大量 API 和 Web 服务当然有其用途! XML 也有类似的 - 以防将来您需要将 XML 反序列化为 C# 对象:xmltocsharp.azurewebsites.net
      • 只是为了彻底摆脱它 - Visual Studio(2010 及更高版本)有能力在本地完成! (我才发现这一点)。单击 Edit > Paste Special > Paste JSON (or XML) As Classes(假设您在 .cs 文件中)。 我以前怎么不知道这个?! 看到这个链接:visuallylocated.com/post/2015/10/05/…
      • @GeoffJames 你是我的连载英雄
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      • 2019-01-02
      相关资源
      最近更新 更多