【问题标题】:DeserializeObject json c#反序列化对象json c#
【发布时间】:2018-08-01 17:33:03
【问题描述】:

我有

 dynamic json

"items": {
          "ids": [
            "some text",
            "some text",
          ],

        },

我尝试添加一些 id 但错误

我的尝试

     List<string> list_json = new List<string>();
 list_json.Add('some text2');
            dynamic json_response = JsonConvert.DeserializeObject(resp);
        json_response.items.ids = JsonConvert.SerializeObject(list_json);

但如果我检查我的结果,我会得到 ​​p>

"ids": 
 "[\"some text2\"]",

怎么了?

【问题讨论】:

  • 这是预期的输出:JsonConvert.SerializeObject returns a string,在本例中是 JSON stringcontent["some text2"]。当使用 string 构建进一步的输出时,“额外的东西”就会出现。也可能是:json_response.items.ids = "\"Honey,\" I'm home!";
  • (tldr;将 list 分配给 id 字段,以便将集合正确序列化为响应 JSON 的一部分)
  • 您必须创建items 对象。 json_response.items = new { ids = ... }

标签: c# arrays json


【解决方案1】:

我没有使用动态,而是为您尝试使用的 JSON 创建了对象。像这样的东西会起作用:

void Main()
{
     var jsonString = @"{""Items"": {
                         ""Ids"": [
                             ""sometext"",
                             ""sometext""
                           ]
                        }}";

    var items = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(jsonString);
}


public class RootObject {
    public Items Items {get;set;}
}

public class Items {
    public List<string> Ids {get;set;}
}

这样您就可以访问 Id 列表

var ids = items.Ids

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-28
    • 2015-08-05
    • 2018-10-03
    相关资源
    最近更新 更多