简体   繁体   中英

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. 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?

my 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#

 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:

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. Try using the above format and then use Json.NET to convert your class to JSON like this:

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

[
  {
    "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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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