【问题标题】:How do i add info from 2 different arrays to a file?如何将来自 2 个不同数组的信息添加到文件中?
【发布时间】:2017-06-01 16:08:01
【问题描述】:

我有两个长度相同的数组,我想使用它们的内容。当我保存到 json 文件时,数组 a 和 b 的 index[0] 应该一起使用。我猜我需要通过它们来访问每个索引并将内容保存到模板 json 中。我也希望它返回一个 toString() 格式的 json,所以每个索引的每次迭代都会返回一些东西。

 public string Show(string[] id, string[] msg)
   {
   // opening code for json file with jobject and jsontexreader
   for (int i = 0; i <= id.Length; i++ )
      {                    
                Newid = id[i];
                Newmsg = msgs[i];
                // setting the data to the json file
                JObject temp = (JObject)o1.SelectToken(path1);
                temp["data"] = msg;
                JObject tem = (JObject)o1.SelectToken(path2);
                tem["ksid"] = id;

        }
       return ??;    

}

【问题讨论】:

标签: c# arrays json save


【解决方案1】:

这是一个完成你想做的事情的简单例子

string Show(string[] id, string[] msg)
{
    if (id.Length != msg.Length) 
        throw new Exception(nameof(id) + " is not the same length as " + nameof(msg));

    List<object> data = new List<object>();

    for (int i = 0; i < id.Length; i++)
    {
        data.Add(new
        {
            Ksid = id[i],
            Data = msg[i]
        });
    }

    return Newtonsoft.Json.JsonConvert.SerializeObject(data);
}

【讨论】:

  • 如何将 Ksid 和数据添加到 json 文件模板中?假设我有一个以下的 json 文件,我会将数据和 id 放入其中。然后在ti复制此json格式后,我想输出添加了新信息的json {“messageR”:{“appId”:“myApp”,“messages”:{“message”:{“content”:{“priorityService” : "false", "data": "测试消息", "mimeType": "text/plain" }, } } } }
  • 是的,我试过了,我不得不调整一些其他的东西,但是谢谢。
猜你喜欢
  • 2021-10-13
  • 1970-01-01
  • 1970-01-01
  • 2015-10-04
  • 2012-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-15
相关资源
最近更新 更多