简体   繁体   English

如何将我的C#数组转换为json?

[英]how to convert my c# array to json?

I was trying to use json for my mobile app, uploadt the file to file hosting site at retrieve it using http. 我试图将json用于我的移动应用程序,然后使用http将文件上传到文件托管站点。 Now I'm having a problem because I'm trying to pass it in a list view and it doesnt retrieve any data. 现在,我遇到了问题,因为我试图在列表视图中传递它,并且它不检索任何数据。 I already test it in jsontoc# but I still think that there's something wrong with my json.. can you tell me if I'm doing it right or can you tell me whats wrong with it? 我已经在jsontoc#中对其进行了测试,但是我仍然认为json出了点问题。您能告诉我我做得对吗,还是可以告诉我它出了什么问题?

my 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
    }       
  ]
} 
]

and here is my array in c# 这是我在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                   
            },              
        } 

Your JSON has this format: 您的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; }
}

You have an array of Mountains so it will not conform to the format. 您有Mountains的数组,因此它与格式不符。 Try using the above format and then use Json.NET to convert your class to JSON like this: 尝试使用上述格式,然后使用Json.NET将类转换为JSON,如下所示:

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

The JSON for a list of the class Mountain is 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
  }       
]

The JSON you have is an array of a class that contains a property public List<Mountain> MountainList; 您拥有的JSON是一个类数组,其中包含属性public List<Mountain> MountainList;

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

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