简体   繁体   中英

I can't deserialize JSON object like I want

I have a web response like this:

[{
  "st1": [
    "folio1",
    "folio2"
  ],
  "st2": [
    "folio1"
  ]
}]

This is my code to call my web server:

var response = await client.GetAsync(uri+"server/getSTFolios/");
if (response.IsSuccessStatusCode)
{
 var content = await response.Content.ReadAsStringAsync();
 var Item = JsonConvert.DeserializeObject<List<ST>>(content);
 return Item;
}

This is ST class, to deserialize my response

public class ST
    {
        private string v;

        public ST(string v)
        {
            this.v = v;
        }

        public string st { get; set; }
        public string location { get; set; }
        public string note { get; set; }
        public int pk { get; set; }
        public List<Folio> folios { get; set; } 
        public override string ToString()
        {
           return "ST: " + st;
        }
    }

But I can't obtain my object, I can't deserialize. I obtaint this when I try print Item.ToString()

System.Collections.Generic.List`1[test2.ST]

This is my debugger. 调试我的功能 Thanks

I'm going to guess this is because your trying to deserialize your JSON object with

var Item = JsonConvert.DeserializeObject<List<ST>>(content);

But the response you're receiving isn't in the same class format as ST .

You're trying to convert an object that looks like

{
    "st1": ["folio1","folio2"],
    "st2": ["folio1"]
}

to this

public class ST
{
    public string st { get; set; }
    public string location { get; set; }
    public string note { get; set; }
    public int pk { get; set; }
    public List<Folio> folios { get; set; } 
}

They share no properties or anything at all. That's why, when debugging and hovering over Item , you do see a single object in that list, but all the values are null. The JsonConvert.DeserializeObject tried to convert your response into the format of ST but found no matching properties, and simply created an empty ST .

If you were to receive a response with more than one object like

[{
    "st1": ["folio1","folio2"],
    "st2": ["folio1"]
},
{
    "st1": ["folio1","folio2"],
    "st2": ["folio1"]
}]

When hovering over Item , you'll have 2 objects full of null values.

Edit

You need to make your server respond with objects that look like the ST class. For example, if you had a response that looked something like this, I assume it would work:

[{
    "st": "some string",
    "location": "some string",
    "note": "some string",
    "pk": 123,
    "folios" : 
    [{ 
        "pk": 123,
        "number": "some string" 
     },
     { 
        "pk": 123,
        "number": "some string" 
     }]
}]

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