JSON字符串反序列化的C#问题

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

JSON string deserialization c# issue

问题

I found solution [JsonPropertyName("currentPage")] attributes should be added for each property or second and better solution add camelCaseOption like this

var options = new JsonSerializerOptions
{
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase
};

// Act
var pagedResult = JsonSerializer.Deserialize<PagedResult<UserDtoTest>>(jsonString, options);

I have those classes and I want to test if JSON string serialization and deserialization works properly, but test fails as pagedResult I get after deserialization on JSON string contains only default value.

public abstract class PagedResultBase
{
    public int CurrentPage { get; }
    public int ResultsPerPage { get; }
    public int TotalPages { get; }
    public long TotalResults { get; }

    protected PagedResultBase()
    {
    }

    protected PagedResultBase(int currentPage, int resultsPerPage,
        int totalPages, long totalResults)
    {
        CurrentPage = currentPage > totalPages ? totalPages : currentPage;
        ResultsPerPage = resultsPerPage;
        TotalPages = totalPages;
        TotalResults = totalResults;
    }
}
public class PagedResult<T> : PagedResultBase
{
    public List<T> Items { get; set; }

    public bool IsEmpty => Items == null || !Items.Any();
    public bool IsNotEmpty => !IsEmpty;

    public PagedResult()
    {
        Items = new List<T>();
    }

    public PagedResult(List<T> items,
        int currentPage, int resultsPerPage,
        int totalPages, long totalResults) :
        base(currentPage, resultsPerPage, totalPages, totalResults)
    {
        Items = items;
    }

    public static PagedResult<T> Create(List<T> items,
        int currentPage, int resultsPerPage,
        int totalPages, long totalResults)
        => new(items, currentPage, resultsPerPage, totalPages, totalResults);

    public static PagedResult<T> From(PagedResultBase result, List<T> items)
        => new(items, result.CurrentPage, result.ResultsPerPage,
            result.TotalPages, result.TotalResults);

    public static PagedResult<T> Empty => new();
}

and

public class UserDtoTest
{
    [JsonPropertyName("name")]
    public string Name { get; set; }
    [JsonPropertyName("active")]
    public bool Active { get; set; }
}

when I try to deserialize json string, it returns PagedResult with default values. Any ideas? Here is my Test

[Fact]
public void ReturnsPagedResultWithCorrectProperties()
{
    // Arrange

    string jsonString = @"{
          ""items"": [
            {
              ""name"": ""anatolijs"",
              ""active"": true
            },
            {
              ""name"": ""trololo"",
              ""active"": true
            },
            {
              ""name"": ""rindām"",
              ""active"": true
            },
            {
              ""name"": ""terepere"",
              ""active"": true
            }
          ],
          ""isEmpty"": false,
          ""isNotEmpty"": true,
          ""currentPage"": 1,
          ""resultsPerPage"": 10,
          ""totalPages"": 1,
          ""totalResults"": 4
        }";

    // Act
    var pagedResult = JsonSerializer.Deserialize<PagedResult<UserDtoTest>>(jsonString);
    var serializedJsonString = JsonSerializer.Serialize<PagedResult<UserDtoTest>>(pagedResult);

    // Assert
    jsonString.Should().Be(serializedJsonString);
}

One constraint: I have to use using System.Text.Json.Serialization;

英文:

I found solution [JsonPropertyName("currentPage")] attributes should be added for each property or second and better solution add camelCaseOption like this

var options = new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase
            };

            // Act
            var pagedResult = JsonSerializer.Deserialize&lt;PagedResult&lt;UserDtoTest&gt;&gt;(jsonString, options);

I have those classes and I want to test if JSON string serialization and deserialization works properly, but test fails as pagedResult I get after deserialization on JSON string contains only default value.

public abstract class PagedResultBase
{
    public int CurrentPage { get; }
    public int ResultsPerPage { get; }
    public int TotalPages { get; }
    public long TotalResults { get; }

    protected PagedResultBase()
    {
    }

    protected PagedResultBase(int currentPage, int resultsPerPage,
        int totalPages, long totalResults)
    {
        CurrentPage = currentPage &gt; totalPages ? totalPages : currentPage;
        ResultsPerPage = resultsPerPage;
        TotalPages = totalPages;
        TotalResults = totalResults;
    }
}
public class PagedResult&lt;T&gt; : PagedResultBase
{
    public List&lt;T&gt; Items { get; set; }

    public bool IsEmpty =&gt; Items == null || !Items.Any();
    public bool IsNotEmpty =&gt; !IsEmpty;

    public PagedResult()
    {
        Items = new List&lt;T&gt;();
    }

    public PagedResult(List&lt;T&gt; items,
        int currentPage, int resultsPerPage,
        int totalPages, long totalResults) :
        base(currentPage, resultsPerPage, totalPages, totalResults)
    {
        Items = items;
    }

    public static PagedResult&lt;T&gt; Create(List&lt;T&gt; items,
        int currentPage, int resultsPerPage,
        int totalPages, long totalResults)
        =&gt; new(items, currentPage, resultsPerPage, totalPages, totalResults);

    public static PagedResult&lt;T&gt; From(PagedResultBase result, List&lt;T&gt; items)
        =&gt; new(items, result.CurrentPage, result.ResultsPerPage,
            result.TotalPages, result.TotalResults);

    public static PagedResult&lt;T&gt; Empty =&gt; new();
}

and

public class UserDtoTest
        {
            [JsonPropertyName(&quot;name&quot;)]
            public string Name { get; set; }
            [JsonPropertyName(&quot;active&quot;)]
            public bool Active { get; set; }
        }

when I try to deserialize json string it returns PagedResult<UserDtoTest> with default values, any ideas? Here is my Test

[Fact]
        public void ReturnsPagedResultWithCorrectProperties()
        {
            // Arrange

            string jsonString = @&quot;{
                  &quot;&quot;items&quot;&quot;: [
                    {
                      &quot;&quot;name&quot;&quot;: &quot;&quot;anatolijs&quot;&quot;,
                      &quot;&quot;active&quot;&quot;: true
                    },
                    {
                      &quot;&quot;name&quot;&quot;: &quot;&quot;trololo&quot;&quot;,
                      &quot;&quot;active&quot;&quot;: true
                    },
                    {
                      &quot;&quot;name&quot;&quot;: &quot;&quot;rindām&quot;&quot;,
                      &quot;&quot;active&quot;&quot;: true
                    },
                    {
                      &quot;&quot;name&quot;&quot;: &quot;&quot;terepere&quot;&quot;,
                      &quot;&quot;active&quot;&quot;: true
                    }
                  ],
                  &quot;&quot;isEmpty&quot;&quot;: false,
                  &quot;&quot;isNotEmpty&quot;&quot;: true,
                  &quot;&quot;currentPage&quot;&quot;: 1,
                  &quot;&quot;resultsPerPage&quot;&quot;: 10,
                  &quot;&quot;totalPages&quot;&quot;: 1,
                  &quot;&quot;totalResults&quot;&quot;: 4
                }&quot;;
            
            // Act
            var pagedResult = JsonSerializer.Deserialize&lt;PagedResult&lt;UserDtoTest&gt;&gt;(jsonString);
            var serializedJsonString = JsonSerializer.Serialize&lt;PagedResult&lt;UserDtoTest&gt;&gt;(pagedResult);

            // Assert
            jsonString.Should().Be(serializedJsonString);
        }

one constrain I have to use using System.Text.Json.Serialization;

答案1

得分: 1

问题在于你的基类中没有设置,你可以修复它。

public abstract class PagedResultBase
{
    public int CurrentPage { get; init; }
    public int ResultsPerPage { get; init; }
    public int TotalPages { get; init; }
    public long TotalResults { get; init; }

    // ....其他代码

}

如果你想摆脱 PropertyName 特性,你需要不同的选项。

var options = new JsonSerializerOptions
{
    PropertyNameCaseInsensitive = true
};

var pagedResult = System.Text.Json.JsonSerializer.Deserialize<PagedResult<UserDtoTest>>(jsonString, options);
英文:

the problem is that you don't have set in your base class , you can fix it

public abstract class PagedResultBase
{
	public int CurrentPage { get; init; }
	public int ResultsPerPage { get; init; }
	public int TotalPages { get; init; }
	public long TotalResults { get; init; }

    // ....another code

}

and you need different option is you want to get rid of PropertyName atribute

	var options = new JsonSerializerOptions
	{
		PropertyNameCaseInsensitive = true
	};

	var pagedResult = System.Text.Json.JsonSerializer.Deserialize&lt;PagedResult&lt;UserDtoTest&gt;&gt;(jsonString,options);

huangapple
  • 本文由 发表于 2023年3月1日 14:51:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/75600383.html
匿名

发表评论

匿名网友

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

确定