简体   繁体   中英

Deserialize Json into class object in C#

I am trying to convert json to C# object.

My test code:

public class testvm
{
   public List<testclass> results { get; set; }    
}    

public class testclass
{
   public string item1 { get; set; }

   [JsonProperty("string")]
   public string item2 { get; set; }
}    

static void jsonfun()
{    
   try
   {
      string json1 = @"{
      ""results"": [{
      ""item1"": ""testitem"" ,
      ""item2"": {
      ""string"": ""testitem2""
      }
      }]
      }";

      var obj1 = JsonConvert.DeserializeObject<testvm>(json1);
      }
      catch (Exception ex)
      { }
}

And output of above code as below Output

AS we can see item2 is becoming null because json has one extra string tag. Any suggestion how to map item2?

The testclass does not match the JSON object's format.

Your JSON looks like:

{
    "results": [
        {
            "item1": "testitem" ,
            "item2": {
                "string": "testitem2"
            }
        }
    ]
}

So you models should look like:

public class TestClass
{
    public string item1 { get; set; }
    public TestClass2 item2 { get; set; }
}

public class TestClass2
{
    [JsonProperty("string")]
    public string someValue { get; set; }

}

And if you want to map it a specific client model

public class ClientModel {
    public string item1 {get;set;}
    public string item2 {get;set;}

}


// After deserialization do the map
var apiModel = JsonConvert.Deserialize([...])

var clientModel = new ClientModel {
  item1 = apiModel.item1,
  item2 = apiModel.item2.someValue
}

Update testclass to this: item2 is some how structure like a Dictionary.

public class testclass
{
    public string item1 { get; set; }

    [JsonProperty("item2")]
    public Dictionary<string, string> item2 { get; set; }
}

Firstly - I recommend you to use System.Text.Json instead of Newtonsoft.Json.

In .NET Core 3.0 and .NET 5 it works faster.

Then - you shouldn't use [JsonProperty()].

How to use System.Text.Json:

public class testvm
{
   public List<testclass> results { get; set; }
}

public class testclass
{
   public string item1 { get; set; }

   public string item2 { get; set; }
}

static void Main(string[] args)
{
   testvm objBeforeSerialization = new testvm() { results = new List<testclass>() { new testclass() { item1 = "myItem1", item2 = "myItem2" } } };
            
   string myJson = JsonSerializer.Serialize(objBeforeSerialization);
                        
   testvm objAfterSerialization = JsonSerializer.Deserialize<testvm>(myJson);
}

JSON in string format will be like:

string stringObject = @"{""results"":[{""item1"":""myItem1"",""item2"":""myItem2""}]}";

You can read more about System.Text.Json in official Microsoft documentation .

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