Cannot convert type 'Newtonsoft.Json.Linq.JProperty' to 'System.Collections.Generic.KeyValuePair'

84 Points
27 Posts

I'm facing following runtime error

  Message=Cannot convert type 'Newtonsoft.Json.Linq.JProperty' to 'System.Collections.Generic.KeyValuePair<string,Newtonsoft.Json.Linq.JToken>'
  Source=<Cannot evaluate the exception source>
<Cannot evaluate the exception stack trace>

I'm trying following code:

using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Linq;
using System.Text;

// Function to convert JSON string to C# class as a string
public static string ConvertJsonToCSharpClass(string jsonString)
    // Parse the JSON string into a dynamic JObject
    dynamic json = JObject.Parse(jsonString);

    // Generate the C# code for the class using StringBuilder
    var stringBuilder = new StringBuilder();
    stringBuilder.AppendLine("public class RootObject");

    // Loop through all the properties in the JObject and generate a property for each one
    foreach (KeyValuePair<string, JToken> property in json)
        string propertyName = property.Key;
        JTokenType propertyType = property.Value.Type;
        string propertyTypeName = GetCSharpTypeName(propertyType);

        stringBuilder.AppendLine($"    public {propertyTypeName} {propertyName} {{ get; set; }}");


    // Return the C# class as a string
    return stringBuilder.ToString();

// Helper function to get the C# type name from a JTokenType
private static string GetCSharpTypeName(JTokenType type)
    switch (type)
        case JTokenType.Boolean:
            return "bool";
        case JTokenType.Integer:
            return "int";
        case JTokenType.Float:
            return "float";
        case JTokenType.String:
            return "string";
        case JTokenType.Date:
            return "DateTime";
        case JTokenType.Array:
            return "List<object>";
        case JTokenType.Object:
            return "object";
            return "object";
Views: 198
Total Answered: 1
Total Marked As Answer: 0
Posted On: 05-May-2023 08:11

Share:   fb twitter linkedin
12 Points
6 Posts

It looks like the error is related to the KeyValuePair type that is used in the foreach loop to iterate through the properties of the JObject. This is because the Properties() method of the JObject returns a collection of JProperty objects instead of a collection of key-value pairs.

To fix this error, you can change the type of the property variable in the foreach loop to JProperty instead of KeyValuePair<string, JToken>. Here's the updated code snippet:

foreach (JProperty property in json.Properties())
        string propertyName = property.Name;
        JTokenType propertyType = property.Value.Type;
        string propertyTypeName = GetCSharpTypeName(propertyType);

        stringBuilder.AppendLine($"    public {propertyTypeName} {propertyName} {{ get; set; }}");
Posted On: 06-May-2023 00:19
 Log In to Chat