简体   繁体   中英

Deserialize JsonElement after posting multiple objects using fetch

I am trying to post multiple objects to.core 3.1 API using fetch. I've managed to recieve the result as a JsonElement, but I can't manage to deserialize it.

JS data & Fetch:

       const users = [
            {
                ID: 1,
                Firstname: "MyFirstname",
                Lastname: "MyLastname"
            },
            {
                ID: 2,
                Firstname: "Jeff",
                Lastname: "Troll"
            }
        ];

        const company = {
            ID: 1,
            Companyname: "Stackoverflow",
            Location: "Unknown"
        };

        await fetch(URL, {
            method: "POST",
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
            users: users,
            company:company
           })
        })
            .then(response => {
                response.text().then(function (text) {
                    alert(text);
                });
            });

The post gets through to my action and I can see the JSON result, but I can't manage to deserialize it.

My action:

        [HttpPost]
        public async Task<ActionResult<Users>> Post([FromBody]JsonElement data)
        {
            try
            {
                var users = JsonSerializer.Deserialize<Users>(data.GetRawText());
                var company = JsonSerializer.Deserialize<Company>(data.GetRawText());
                ...
            }
        }

users and company properties is empty after I try to deserialize them. Not sure what I am doing wrong, and how to do a simple deserialize without creating a specific Model for this (I would prefer not to since it's a post which I am only using once.

JsonElement data looks like this:

ValueKind = Object : "
{"users":[{"ID":1,"Firstname":"MyFirstname","Lastname":"MyLastname"},
{"ID":2,"Firstname":"Jeff","Lastname":"Troll"}],
"company":
{"ID":1,"Companyname":"Stackoverflow","Location":"Unknown"}}
"

Is JsonElement the correct choice for this? Or can I solve it on some other way?

@arkhz To answer your question kindly find below the implementation or solution.

    public class Users
    {
        public int ID { get; set; }
        public string Firstname { get; set; }
        public string Lastname { get; set; }
    }

    public class Company
    {
        public int ID { get; set; }
        public string Companyname { get; set; }
        public string Location { get; set; }
    }

        [HttpPost]
        public async Task<ActionResult<Users>> Post([FromBody]JsonElement data)
        {
            try
            {
                var users = JsonSerializer.Deserialize<List<Users>>(data.GetRawText());
                var company = JsonSerializer.Deserialize<Company>(data.GetRawText());
                return Ok(new { message = "", data = users });
            }
            catch
            {
                return Ok(new { message = "", data = data });
            }
        }

so specifically your json object for users and companys were a List of Users Object or a Collection of users object.

find below a sample JsonString sent as test

{
    "users": [
        {
            "ID": 1,
            "Firstname": "MyFirstname",
            "Lastname": "MyLastname"
        },
        {
            "ID": 2,
            "Firstname": "Jeff",
            "Lastname": "Troll"
        }
    ],
    "company": {
        "ID": 1,
        "Companyname": "Stackoverflow",
        "Location": "Unknown"
    }
}

please you can also create your body like this.

var body = {"users": users, "company":company};

 await fetch(URL, {
            method: "POST",
            headers: {
                'Content-Type': 'application/json'
            },
            body:body
        })
            .then(response => {
                response.text().then(function (text) {
                    alert(text);
                });
            });

Please this works, i have tested over an over again. i can share you screenshot of tested postman. with vscode.

Thanks

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