【问题标题】:How can I fill nested simple array type json after execution Restsharp?执行Restsharp后如何填充嵌套的简单数组类型json?
【发布时间】:2020-05-14 12:47:51
【问题描述】:

我有一个关于字符串 json 数据解析的问题。实际上,我遇到了一些问题。我的 json 在

之后

"response = clientRest.Execute(request);" 执行。但在 FeaturePreference.cs 中, FeaturePreference.Rootobject 是空的。所有标签 = null 值 = 0。有什么问题吗? 统计数据值:

我的 Json(响应):

[
    {
        "Label": "Spa Merkezi",
        "Value": 3.7037037037037037
    },
    {
        "Label": "Güzellik Merkezi",
        "Value": 0.92592592592592593
    },
    {
        "Label": "Açık Havuz",
        "Value": 4.62962962962963
    },
    {
        "Label": "Yerli İçecek",
        "Value": 0.92592592592592593
    }
]

    public class FeaturePreference
    {

        public class Rootobject
        {
            public Result[] Result { get; set; }
        }

        public class Result
        {
            public string Label { get; set; }
            public float Value { get; set; }
        }

    }

我的完整代码:


        private static void DataParseForSomeShit(string userid)
        {

            var clientRest = new RestClient("https://xxxx.azurewebsites.net/api/");
            var request = new RestRequest(Method.POST);
            request.Resource = $"foobyuserid/?userid={userid}&code=g2ehoC4tycM6H2TcJUWszTlWa6lXfsA==";
            request.RequestFormat = DataFormat.Json;

            IRestResponse response = null;
            try
            {
                response = clientRest.Execute(request);
                string json = "{ \"Result\" : " + response.Content.Trim('"').Replace('\\', ' ') + "}";
                var stats = JsonConvert.DeserializeObject<FeaturePreference.Rootobject>(json); // Empthy items !
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                Trace.WriteLine(ex.Message);
            }

            if (string.IsNullOrEmpty(response.Content))
            {

            }

        }

【问题讨论】:

    标签: c# .net asp.net-mvc rest json.net


    【解决方案1】:

    您似乎正在尝试在反序列化之前手动操作 JSON 以尝试适合您的模型。不要那样做。相反,反序列化为与您的 JSON 匹配的正确结构。您的 JSON 表示 FeaturePreference.Result 的数组,因此您应该反序列化为 FeaturePreference.Result[](或 List&lt;FeaturePreference.Result&gt;,如果您愿意)。

    尝试改变这个:

    string json = "{ \"Result\" : " + response.Content.Trim('"').Replace('\\', ' ') + "}";
    var stats = JsonConvert.DeserializeObject<FeaturePreference.Rootobject>(json); // Empthy items !
    

    到这里:

    var stats = JsonConvert.DeserializeObject<FeaturePreference.Result[]>(response.Content);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-03-26
      • 2021-01-06
      • 2023-03-26
      • 2020-06-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多