简体   繁体   English

使用 fetch 发布多个对象后反序列化 JsonElement

[英]Deserialize JsonElement after posting multiple objects using fetch

I am trying to post multiple objects to.core 3.1 API using fetch.我正在尝试使用 fetch 将多个对象发布到.core 3.1 API。 I've managed to recieve the result as a JsonElement, but I can't manage to deserialize it.我已经设法将结果作为 JsonElement 接收,但我无法对其进行反序列化。

JS data & Fetch: JS 数据和获取:

       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.该帖子通过了我的操作,我可以看到 JSON 结果,但我无法对其进行反序列化。

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.不知道我做错了什么,以及如何在不为此创建特定 Model 的情况下进行简单的反序列化(我不希望这样做,因为这是我只使用一次的帖子。

JsonElement data looks like this: JsonElement 数据如下所示:

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? JsonElement 是正确的选择吗? Or can I solve it on some other way?或者我可以通过其他方式解决它吗?

@arkhz To answer your question kindly find below the implementation or solution. @arkhz 要回答您的问题,请在实施或解决方案下方找到。

    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.所以特别是您的 json object 用户和公司是用户列表 Object 或用户集合 ZA8CFDE63931BD59EB26AC9C64。

find below a sample JsonString sent as test在下面找到作为测试发送的示例 JsonString

{
    "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.我可以分享你测试过的 postman 的截图。 with vscode.用 vscode。

Thanks谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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