我有一个像这样的json对象数组:
[{
"Time-VitalsTime": "2019-06-22T01:01:00",
"TimeToEstimate-VitalsTime": 10,
"TimeToEstimate-1unit": 5,
"TimeToEstimate-2units": 9,
"TimeToEstimate-3units": 21,
"TimeToEstimate-1week": 13,
"TimeToEstimate-2weeks": 16,
"TimeToEstimate-3weeks": 20
}, {
"Time-VitalsTime": "2019-06-22T01:02:00",
"TimeToEstimate-VitalsTime": 8,
"TimeToEstimate-1unit": 10,
"TimeToEstimate-2units": 5,
"TimeToEstimate-3units": 9,
"TimeToEstimate-1week": 18,
"TimeToEstimate-2weeks": 15,
"TimeToEstimate-3weeks": 32
}, {
"Time-VitalsTime": "2019-06-22T01:03:00",
"TimeToEstimate-VitalsTime": 10,
"TimeToEstimate-1unit": 8,
"TimeToEstimate-2units": 10,
"TimeToEstimate-3units": 5,
"TimeToEstimate-1week": 15,
"TimeToEstimate-2weeks": 14,
"TimeToEstimate-3weeks": 16
},
并且我需要将其设置为这种形状(根据api文档):
{
"data":
[
<model-specific-data-structure>
]
}
用于生成上面的字符串的代码是:
public string ConvertCsvFileToJsonObject(string path)
{
var csv = new List<string[]>();
var lines = File.ReadAllLines(path);
foreach (string line in lines)
csv.Add(line.Split(','));
var properties = lines[0].Split(',');
var listObjResult = new List<Dictionary<string, string>>();
for (int i = 1; i < lines.Length; i++)
{
var objResult = new Dictionary<string, string>();
for (int j = 0; j < properties.Length; j++)
objResult.Add(properties[j], csv[i][j]);
listObjResult.Add(objResult);
}
var newlistObjResult = new List<Dictionary<dynamic,dynamic>>();
var count = 0;
foreach (var dictionary in listObjResult)
{
Console.WriteLine($"Dictionary I am currently on: {count}");
var newDict = new Dictionary<dynamic, dynamic>();
foreach (var item in dictionary)
{
DateTime dateTime;
if (DateTime.TryParse(item.Value, out dateTime))
{
newDict.Add(item.Key, dateTime);
continue;
}
else
{
try
{
var asInt = Convert.ToInt32(item.Value);
newDict.Add(item.Key, asInt);
}
catch (Exception e)
{
var ex = e.Message;
}
}
}
newlistObjResult.Add(newDict);
count += 1;
}
var result2 = JsonConvert.SerializeObject(newlistObjResult);
return result2;
}
然后我正在使用它:
request.Content = new StringContent(JsonConvert.SerializeObject(stringgeneratedabove));
序列化以发送到REST api。我从通话中得到的错误是: “ {\” error \“:\”字符串索引必须为整数\“}”
一个朋友说,我需要在名为“ data”的属性中传递数组。在进行了大量在线搜索之后,我不知道从哪里开始。我试图做这样的事情:
[DataContract]
public class CsvDataClass
{
[DataMember]
public List<Dictionary<object, object>> CsvData { get; set; }
[DataMember]
public Dictionary<object, object>[] Data
{
get { return CsvData.ToArray(); }
}
}
基于朋友说的话,但无法实现。我搜索了“更改json c#的形状”或“将json数组传递到属性中”,并且还阅读了有关json对象的常规文档,但没有任何点击。
答案 0 :(得分:1)
要使json变成所需的形状,我这样做:
var result = "{\"data\":" + jsonString + "}";
其中jsonString等于此线程顶部显示的对象数组,因此我只是手动添加了这些值。
我还必须更改此设置:
request.Content = new StringContent(JsonConvert.SerializeObject(result))
request.Content.Headers.ContentType = new
MediaTypeHeaderValue("application/json");
收件人:
request.Content = new StringContent(asjson.ToString(), Encoding.UTF8, "application/json");