更正无效的 Json 字符串并将其转换为 C# Class

Correct an invalid Json string and convert it to C# Class

我想将以下 json 字符串转换为 C# class。但我无法弄清楚......即使使用像“json2csharp”这样的在线转换器程序。

{[
  {
    "tmcp_post_fields": [],
    "product_id": 703,
    "per_product_pricing": true,
    "cpf_product_price": "45",
    "variation_id": false,
    "form_prefix": "",
    "tc_added_in_currency": "EUR",
    "tc_default_currency": "EUR"
  }
]}

有人可以帮助我吗? 我尝试了这些错误的变体:

public class myclass
{
        public List<object> tmcp_post_fields { get; set; }
        public int product_id { get; set; }
        public bool per_product_pricing { get; set; }
        public string cpf_product_price { get; set; }
        public bool variation_id { get; set; }
        public string form_prefix { get; set; }
        public string tc_added_in_currency { get; set; }
        public string tc_default_currency { get; set; }
}

或此 class

的列表
List<myclass>

我用这个代码来转换它

if (value != null && value.GetType().FullName.StartsWith("Newtonsoft.Json"))
{
     string s = value.GetType().FullName;

     if (value.GetType().FullName.EndsWith("JArray"))
     {
           JArray ja = (JArray)Convert.ChangeType(value, typeof(JArray));

           if (ja.HasValues)
           {

                try
                {
                    return ja.ToObject<myclass>();       //this
                    return ja.ToObject<List<myclass>>(); //or this does NOT work for me
                }
                catch { }

                return value;
           }
           else
                return null;
}

我总是遇到这个错误:

Newtonsoft.Json.JsonReaderException - Error reading string. Unexpected token

如果我删除第一个打开和关闭 {} 它会起作用。

您的 json 无效,它的两侧有额外的 {}。试试这个

var json=...your json

json=json.Substring(1,json.Length-2);

var jsonDeserialized = JsonConvert.DeserializeObject<Data[]>(json);

和class

public class Data
    {
        public List<object> tmcp_post_fields { get; set; }
        public int product_id { get; set; }
        public bool per_product_pricing { get; set; }
        public string cpf_product_price { get; set; }
        public bool variation_id { get; set; }
        public string form_prefix { get; set; }
        public string tc_added_in_currency { get; set; }
        public string tc_default_currency { get; set; }
    }

另一种选择是使用插入字符串。这个选项甚至更好,因为您也可以使用解析 json 字符串。

json=json.Insert(1,"result:");
var jsonDeserialized = JsonConvert.DeserializeObject<Root>(json);

和class

public class Root
{
    public Data[] result {get; set;}
}

产出

{
  "result": [
    {
      "tmcp_post_fields": [],
      "product_id": 703,
      "per_product_pricing": true,
      "cpf_product_price": "45",
      "variation_id": false,
      "form_prefix": "",
      "tc_added_in_currency": "EUR",
      "tc_default_currency": "EUR"
    }
  ]
}