【问题标题】:parse json response c#解析 json 响应 c#
【发布时间】:2019-03-07 06:17:32
【问题描述】:

我创建了小班

class JsonResponse
{
    public string Response { get; set; }
}

然后在我的程序中我发送一些 json 数据并等待商店回复以下变量

var ResultJSON = Post(uri, values);

在解析时我得到了

服务错误:无法将“System.String”类型的对象转换为类型 'App.someclass+JsonResponse'

【问题讨论】:

  • 请参考帖子here的答案以获得答案
  • 那个看不懂,能不能修改我的代码?
  • 出现了与初始问题无关的简单错误。请关闭并删除

标签: c# json parsing post


【解决方案1】:
using Newtonsoft.Json;

class JsonResponse
{
    public string Response { get; set; }
}

class Utility
{
    public JsonResponse JsonDeserialisation(string response)
    {
        TextReader textReader = new StreamReader(response);
        JsonTextReader jsonReader = new JsonTextReader(textReader);
        return JsonSerializer.CreateDefault().Deserialize<JsonResponse>(jsonReader);
    }
}
class Main
{
    static void Program()
    {
        var ResultJSON = "Json String received from post";//Post(uri, values);
        var deserialisedJson = Utility.JsonDeserialisation(ResultJSON);
    }
}

将 newtonSoft.json nuget 包添加到项目中

【讨论】:

    【解决方案2】:

    试试 var Result = new JavaScriptSerializer().Deserialize&lt;JsonResponse&gt;(ResultJSON.**Response**);

    在我看来,您正在尝试从对象而不是字符串响应反序列化

    【讨论】:

      【解决方案3】:

      试试这个,可能会将您的 JSON 文件提供给结果变量。

      var result = Convert.ToString(ResultJSON); 
      

      【讨论】:

        【解决方案4】:

        尝试使用using newtonsoft.json 可下载的here 或使用nuget 包。

        它的功能完全符合您的要求。期待Post 的结果当然是字符串格式。

        var result = JsonConvert.DeserializeObject<JsonResponse>(ResultJSON);
        

        您的 JsonResponse 类必须与您获得的 json 完全相同。因此,请确保如果您在要保存在类中的 json 中获得更多数据,则名称相同。

        如果您还有其他问题,请随时提问。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-03-27
          • 1970-01-01
          • 2020-03-04
          • 2020-06-17
          相关资源
          最近更新 更多