Click here to Skip to main content
15,500,824 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have a json file and json data is something like that:-


{
      "Partdetails ": [
				{
					"key": "pincode",
					"value": "34598702"
				},
				{
					"key": "deliveryStatus",
					"value": "OptedOut"
				},
				{
					"key": "deliveryDate",
					"value": "2022-09-02T00:00:00"
				},
				{
					"key": "Status",
					"value": "successfully dispatch"
				}
			]
}


i have a modal class :

public class Partdetail
 {
     public string key { get; set; }
     public object value { get; set; }
 }


i want to access this json data from json file and bind into a List<partdetail> or in a dictionary whatever suitable for such kind of data.

can any one suggest me the solution

What I have tried:

public static class JsonFileReader
{
    public static T Read<T>(string filePath)
    {
        string text = File.ReadAllText(filePath);
        var json= JsonSerializer.Deserialize<T>(text);
        return json;

    }
}


Partdetails item = JsonFileReader.Read<Partdetails >(@"C:\filepath\data.json");


this code successfully fatch the data from my file but not Deserialize into json.
Posted
Updated 16-Sep-22 15:57pm
v3

You need to use the proper context for deserialization: https://docs.microsoft.com/en-us/dotnet/api/system.text.json.jsonserializer?view=net-6.0[^].
 
Share this answer
 
Comments
Graeme_Grant 16-Sep-22 20:47pm    
Not that simple
Richard MacCutchan 17-Sep-22 4:00am    
I have a sample that pretty much is.
Graeme_Grant 17-Sep-22 7:44am    
I can see that you posted it...
You need to write a custom converter to handle this: How to write custom converters for JSON serialization - .NET | Microsoft Learn[^]. I have also written an article on writing custom converters: Working with System.Text.Json in C#[^]

Here is the converter:
C#
public class DictionaryConverter : JsonConverter<PartDetails>
{
	public override PartDetails? Read(ref Utf8JsonReader reader,
                                      Type typeToConvert, JsonSerializerOptions options)
	{
        if (reader.TokenType != JsonTokenType.StartObject)
            return default;
		
		PartDetails? result = new();

		while (reader.TokenType != JsonTokenType.EndArray)
		{
			reader.Read();

			if (reader.TokenType == JsonTokenType.StartObject)
			{
				string key = string.Empty, value = string.Empty;
				foreach (KeyValuePair<string, JsonNode?> item in
                         JsonSerializer.Deserialize<JsonObject>(ref reader,
                                                                options)!)
				{
					if (item.Key == "key") key = item.Value!.ToString();
					if (item.Key == "value") value = item.Value!.ToString();
				}

				result.Items.Add(key, value);
			}
		}

		reader.Read(); // move to the end of the object

		return result;
	}

	public override void Write(Utf8JsonWriter writer, PartDetails value,
                               JsonSerializerOptions options)
	{
		throw new NotImplementedException();
	}
}

The class used with the converter attached:
C#
[JsonConverter(typeof(DictionaryConverter))]
public class PartDetails
{
	public Dictionary<string, string> Items { get; set; } = new();
}

NOTE: We can't use the attribute JsonPropertyName on the class, so we need to tell the serializer to ignore case:
C#
JsonSerializerOptions options = new()
{
	PropertyNameCaseInsensitive = true,
};

Now we can deserialize the Json data...
C#
PartDetails? list =
    JsonSerializer.Deserialize<PartDetails>(rawJson, options);

foreach (KeyValuePair<string, string> item in list!.Items!)
	Console.WriteLine($"{item.Key}, {item.Value}");
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900