Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
367 views
in Technique[技术] by (71.8m points)

asp.net - Converting json to c# object

I have an api that returns me a json with information about the data transition and an array with data

{
    "code": "200",
    "result": true,
    "message": "",
    "data": {
        "item": [
            {
                "id": "5",
                "descricao": "TesteDesc",
                "observacao": "TesteObs",
                "status": "1"
            },
            {
                "id": "7",
                "descricao": "TesteDesc",
                "observacao": "TesteObs",
                "status": "1"
            },
        ],
        "count": 2
    }
}

I have a class that is referring to the return of items

class Category
 {
     public int Id { get; set; }
     public string Descricao { get; set; }
     public int Status { get; set; }
     public string Observacao { get; set; }
 }

Main.cs

 var stringJson = await response.Content.ReadAsStringAsync();

my string stringJson gets the following value

"

{"code":"200","result":true,"message":"","data":{"item":[{"id":"5","descricao":"TesteDesc","observacao":"TesteObs","status":"1"}],"count":2}}"

but when I try to convert

var Data = JsonConvert.DeserializeObject<IEnumerable<Category>>(stringJson);

error is displayed

Erro: cannot deserialize the current json object (e.g. {"name":"value"}) into type ...

How can I create an array of objects with json data? taking only the date and item

is it possible for me to retrieve the values formally alone, for example I make a variable bool status = jsonConvert.get ("status"); something like that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Frist you outer JSON format is an object, not an array.

You models will like this.

public class Item
{
    public string id { get; set; }
    public string descricao { get; set; }
    public string observacao { get; set; }
    public string status { get; set; }
}

public class Data
{
    public List<Item> item { get; set; }
    public int count { get; set; }
}

public class Category
{
    public string code { get; set; }
    public bool result { get; set; }
    public string message { get; set; }
    public Data data { get; set; }
}

Deserialize json

var Data = JsonConvert.DeserializeObject<Category>(stringJson);
List<Item> items = Data.data.item;
//items get info from items 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...