【问题标题】:parsing string to model将字符串解析为模型
【发布时间】:2017-06-23 03:42:29
【问题描述】:

有这个:

 HttpContent requestContent = Request.Content;
 string jsonContent = requestContent.ReadAsStringAsync().Result;

然后在这个 jsonContent 中:

ID=1234&toName=&fromId=49gjgijl7a4in

我正在尝试在模型中解析:

 Model model = JsonConvert.DeserializeObject<Model>(jsonContent);

但它会引发异常:

解析布尔值时出错。路径 '',第 0 行,第 0 位置

有什么想法吗?

编辑:

我的客户端逻辑:

                var client = new HttpClient();
                var values = new Dictionary<string, string>()
                {
                    {"toId", obj.toId},
                    {"toName", obj.toName},
                    {"fromId", obj.fromId},
                };
                var content = new FormUrlEncodedContent(values);

                var response = await client.PostAsync(apiUrl, content);
                response.EnsureSuccessStatusCode();

【问题讨论】:

标签: c# string parsing


【解决方案1】:

要从 uri 查询字符串中解析参数,请使用 System.Web.HttpUtility 中的这个

var content = Request.Content.ReadAsStringAsync().Result;
var query = HttpUtility.ParseQueryString(content);
var id = query.Get("ID");
var toName = query.Get("toName");

【讨论】:

    【解决方案2】:

    如果您想以Json 对象的形式发送数据,请使用以下代码(客户端):

    var client = new HttpClient();
    
    var jsonObj = (dynamic)new JsonObject();
    jsonObj.toId = obj.toId;
    jsonObj.toName = obj.toName;
    jsonObj.fromId = obj.fromId;
    
    var content = new StringContent(jsonObj.ToString(), Encoding.UTF8, "application/json");
    
    var response = await client.PostAsync(apiUrl, content);
                response.EnsureSuccessStatusCode();
    

    那么你可以在你的问题中使用JsonConvert

    如果您想将数据作为查询字符串发送,然后使用Json

    var dict = HttpUtility.ParseQueryString(jsonContent);
    var json = new JavaScriptSerializer().Serialize(
                        dict.AllKeys.ToDictionary(k => k, k => dict[k]));
    

    然后您可以使用JsonConvert 将其反序列化为您的模型。

    如果您不想更改客户端逻辑:

    var dict = HttpUtility.ParseQueryString(jsonContent);
    
    YourModel model = new YourModel()
    {
        Id = dict.Get("ID"]),
        ToName = dict.Get("toName"),
        FromId = dict.Get("fromId")
    };
    

    【讨论】:

      【解决方案3】:

      Json 内容应该是这样的。检查你的内容

      { 
      "ID":1234,
       "toName":"",
      "fromId": "49gjgijl7a4in"
      }
      

      【讨论】:

      • 我就是这样创作的。但是从 headers 中获取内容后如何将其转换为模型?
      • 有模型的可以试试这个方法:TryUpdateModel(requestContent);
      【解决方案4】:
      HttpContent requestContent = Request.Content;
      string jsonContent = requestContent.ReadAsStringAsync().Result;
      
      //you can split your jsonContent then you use the code
      string[] paramsArrs = jsonContent.Split('&');`
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-02-15
        • 2013-07-09
        • 1970-01-01
        • 1970-01-01
        • 2010-09-06
        • 2014-01-04
        • 2011-03-14
        相关资源
        最近更新 更多