当在 Blazor 创建新行时将列表反序列化为字符串时出现错误?

huangapple go评论59阅读模式
英文:

error when deserialize list to string when create new row blazor?

问题

我在asp.net core blazor上工作,当尝试将列表反序列化为字符串时出现错误,那么请问如何解决这个问题?

错误信息如下:

错误: System.Text.Json.JsonException: 无法将JSON值转换为System.String。路径: $ | 行号: 0 | 行中的字节位置: 1。
---> System.InvalidOperationException: 无法将“StartObject”类型的标记值作为字符串获取。
在System.Text.Json.ThrowHelper.ThrowInvalidOperationException_ExpectedString(JsonTokenType tokenType)
在System.Text.Json.Utf8JsonReader.GetString()

错误发生在以下语句上:

JsonSerializer.DeserializeAsync<string>(responsestream)

导致错误的函数是:

private async Task CreateClick()
{
var deptobj = new ServerNamesClass() { server_Name = server_Name, server_Type = server_Type, operating_System = operating_System, version = version, isActive = isActive };
var request = new HttpRequestMessage(HttpMethod.Post, config["API_URL"] + "ServerNames");
request.Content = new StringContent(JsonSerializer.Serialize(deptobj), null, "application/json");
var client = ClientFactory.CreateClient();
var response = await client.SendAsync(request);
using var responsestream = await response.Content.ReadAsStreamAsync();
string res = await JsonSerializer.DeserializeAsync<string>(responsestream);
await JS.InvokeVoidAsync("alert", res);
await RefreshList();
}

以下是返回的类的数据:

public class ServerNamesClass
{
public int serverID { get; set; }
public string server_Name { get; set; }
public string server_Type { get { get; set; }
public string operating_System { get; set; }
public string version { get; set; }
public bool isActive { get; set; }
}

API控制器:

[HttpPost]
public ActionResult AddServer(ServerNames ServersName)
{
return Ok(_IserverNamesService.Insert(ServersName));
}

英文:

I work on asp.net core blazor i get error when deserialize list to string
so How to solve this issue please ?

error

 Error: System.Text.Json.JsonException: The JSON value could not be converted to System.String. Path: $ | LineNumber: 0 | BytePositionInLine: 1.
 ---&gt; System.InvalidOperationException: Cannot get the value of a token type &#39;StartObject&#39; as a string.
   at System.Text.Json.ThrowHelper.ThrowInvalidOperationException_ExpectedString(JsonTokenType tokenType)
   at System.Text.Json.Utf8JsonReader.GetString()

error generationg on this statment below :

JsonSerializer.DeserializeAsync&lt;string&gt;(responsestream)

function that generate error is

private async Task CreateClick()
    {
        var deptobj = new ServerNamesClass() { server_Name = server_Name, server_Type = server_Type, operating_System = operating_System, version = version, isActive = isActive };
        var request = new HttpRequestMessage(HttpMethod.Post, config[&quot;API_URL&quot;] + &quot;ServerNames&quot;);
        request.Content = new StringContent(JsonSerializer.Serialize(deptobj), null, &quot;application/json&quot;);
        var client = ClientFactory.CreateClient();
        var response = await client.SendAsync(request);
        using var responsestream = await response.Content.ReadAsStreamAsync();
        string res = await JsonSerializer.DeserializeAsync&lt;string&gt;(responsestream);
        await JS.InvokeVoidAsync(&quot;alert&quot;, res);
        await RefreshList();


    }  

data returned on class below :

 public class ServerNamesClass
        {
            public int serverID { get; set; }
            public string server_Name { get; set; }
            public string server_Type { get; set; }
            public string operating_System { get; set; }
            public string version { get; set; }
            public bool isActive { get; set; }
        }

controller api

 [HttpPost]
        public ActionResult AddServer(ServerNames ServersName)
        {
            return Ok(_IserverNamesService.Insert(ServersName));
        }

答案1

得分: 1

使用 ReadFromJsonAsync 替代 ReadAsStreamAsync

修改你的代码:

using var responsestream = await response.Content.ReadAsStreamAsync();

为:

using var responsestream = await response.Content.ReadFromJsonAsync();

或者移除两行代码并换成新的一行:

using var responsestream = await response.Content.ReadAsStreamAsync();
string res = await JsonSerializer.DeserializeAsync<string>(responsestream);

为:

string res = await response.Content.ReadAsStringAsync();
英文:

You have to use ReadFromJsonAsync instead of using ReadAsStreamAsync

Change your code:

using var responsestream = await response.Content.ReadAsStreamAsync();

to:

using var responsestream = await response.Content.ReadFromJsonAsync();

or remove two lines of code and change it to new line:

using var responsestream = await response.Content.ReadAsStreamAsync();
string res = await JsonSerializer.DeserializeAsync&lt;string&gt;(responsestream);

to:

string res = await response.Content.ReadAsStringAsync();

huangapple
  • 本文由 发表于 2023年2月14日 21:32:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75448572.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定