简体   繁体   中英

How to name my json object array in asp.net core

I am trying to name my array of objects, but it lists only the result of the array being created:

public class Listagem {
    public List<Captura> captura { get; set; }
}

my class

public class Captura {
    public int Codigo { get; set; }
    public string FotoURL { get; set; } 
}

my controller

public IactionResult(Listagem models) {

var resultJson = JsonConvert.SerializeObject(models.captura);

...

Current results:

[
   {
     "Cod":11111,
     "photo":xxxx,

Expected outcome:

{
   "captura":[
   {
     "Cod":11111,
     "photo":xxxx,

You have

    var resultJson = JsonConvert.SerializeObject(models.captura);

but you want

    var resultJson = JsonConvert.SerializeObject(models);

Type names don't matter. Local variable names don't matter. The contents of the expression used to get the argument to SerializeObject doesn't matter. Only member names matter.

Most likely, you wrote the above because you have other stuff in models you don't want serialized. In this case, you should do

public class CapturaModel {
    public IList<Captura> captura;
};


    //...
    var resultJson = JsonConvert.SerializeObject(new CapturaModel { captura = models.captura; });

This code also shows why the contents of the expression used get the argument to SerializeObject doesn't matter.

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