【问题标题】:how to convert my c# array to json?如何将我的 c# 数组转换为 json?
【发布时间】:2017-03-07 03:17:47
【问题描述】:

我试图将 json 用于我的移动应用程序,将文件上传到文件托管站点并使用 http 检索它。现在我遇到了一个问题,因为我试图在列表视图中传递它并且它没有检索任何数据。我已经在 jsontoc# 中对其进行了测试,但我仍然认为我的 json 有问题。你能告诉我我做得对吗?或者你能告诉我它有什么问题吗?

我的 json

[
{
"Mountains": [
  {
    "MtName": "TALAMITAM",
    "Masl":  630,
    "Difficulty": 3,
    "Island":  1
    },
    {
    "MtName": "ALTO PEAK",
    "Masl":  1332,
    "Difficulty": 6,
    "Island": 2
    },
    {
    "MtName": "CANDALAGA",
    "Masl":  1232,
    "Difficulty": 7,
    "Island": 3
    }       
  ]
} 
]

这是我在 c# 中的数组

 public static List<Mountain> MountainList = new List<Mountain>()
        {

            new Mountain()
            {
                MtName = "ALTO PEAK",
                Masl = 1332,
                Difficulty = 6,
                Island = 2
            },
            new Mountain()
            {
                MtName = "APO",
                Masl = 2956,
                Difficulty = 7,
                Island = 3                   
            },
            new Mountain()
            {
                MtName = "CANDALAGA",
                Masl = 1232,
                Difficulty = 7,
                Island = 3                   
            },              
        } 

【问题讨论】:

标签: c# json listview http xamarin.android


【解决方案1】:

您的 JSON 格式如下:

public class Rootobject
{
    public Class1[] Property1 { get; set; }
}

public class Class1
{
    public Mountain[] Mountains { get; set; }
}

public class Mountain
{
    public string MtName { get; set; }
    public int Masl { get; set; }
    public int Difficulty { get; set; }
    public int Island { get; set; }
}

您有一个Mountains 数组,因此它不符合格式。尝试使用上述格式,然后使用Json.NET 将您的类转换为 JSON,如下所示:

var ro = new Rootobject();
// more code here to populate the ro properties
var json = JsonConvert.SerializeObject(ro);

【讨论】:

  • 你能告诉我我的 json 的正确格式是什么吗?喜欢第一个答案?因为这就是我正在寻找的......感谢您的回答:D
【解决方案2】:

Mountain 类列表的 JSON 是

[
  {
    "MtName": "TALAMITAM",
    "Masl":  630,
    "Difficulty": 3,
    "Island":  1
  },
  {
    "MtName": "ALTO PEAK",
    "Masl":  1332,
    "Difficulty": 6,
    "Island": 2
  },
  {
    "MtName": "CANDALAGA",
    "Masl":  1232,
    "Difficulty": 7,
    "Island": 3
  }       
]

您拥有的 JSON 是一个包含属性 public List&lt;Mountain&gt; MountainList; 的类的数组

【讨论】:

  • 所以我不必写“山”部分?
  • 不,你不必写山的部分。
猜你喜欢
  • 2012-03-24
  • 1970-01-01
  • 1970-01-01
  • 2015-08-26
  • 1970-01-01
  • 1970-01-01
  • 2021-01-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多