简体   繁体   中英

JSON Deserialize .net Core 3

This one is realy Basic. Deserialize a String with the new System.Text.Json;

namespace test
{
    struct CI {
       public int Id;
       public string Name;
       public string Address;

    }
    public class test{

                        var userlist = "{\"Id\":1,\"Name\":\"Manas\",\"Address\":\"India\"}";
                        var temp2 = JsonSerializer.Deserialize<CI>(userlist,new JsonSerializerOptions { AllowTrailingCommas = true});
    }
}

but doing so
I just get null for Strings and 0 for the Int in temp2

This has to be something simple, but I don´t get it

System.Text.Json doesn't support field serialization . The feature is scheduled for .NET 5.0.

You used public fields instead of public properties. If you tried with properties and exactly the same code:

    struct CI {
       public int Id {get;set;}
       public string Name {get;set;}
       public string Address {get;set;}
    }

You'd get the expected object back:

Id        1 
Name      Manas 
Address   India 

Why?

System.Text.JSON specifically isn't meant to be a Swiss knife JSON deserializer the way JSON.NET is. It's main use case is fast DTO serialization in the HTTP API scenario with minimal allocations, and DTOs use properties.

Properties aren't just fields with getters and setters, they are part of the object's interface. Fields on the other hand are treated as internal state even if they are public. Serializers work with properties by default, with field serialization an optional feature.

That said, value tuples . This is now a fundamental type, which uses fields for performance and reduced copying. Tuples have their place in DTOs, but the current System.Text.Json can't handle them.

Work is already well under way for this , there's already a PR being reviewed but the target version is 5.0

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