Pro*_*mer 0 c# json dictionary
我试图将从相机收到的响应(字符串)拆分为键和值.这是来自IP摄像头的字符串:
{"error":0,"session":678939290,"group":131071}
Run Code Online (Sandbox Code Playgroud)
我想将它们分成没有""的键和数组.例如:
键 <----> 值
错误 0
会议 678939290
第 131071 组
以下是我目前使用的代码:
string tempResponse = serverResponse;
//Remove Left and Right curly braces
tempResponse = tempResponse.Replace("{", "");
tempResponse = tempResponse.Replace("}", "");
//Remove '"' from the string
tempResponse = tempResponse.Replace("\"", "");
//Now Make sure that there is no Space begining and end of the string
tempResponse = tempResponse.TrimStart().TrimEnd();
var items = tempResponse.Split(new[] { ',' }, StringSplitOptions.None)
.Select(s => s.Split(new[] { ':' }));
Dictionary<string, string> camInfoDICT = null; //Stores the camInfo as keys and values
camInfoDICT = new Dictionary<string, string>();
foreach (var item in items)
{
try
{
camInfoDICT.Add(item[0], item[1]);
}
catch (Exception e)
{
Debug.Log("Exception " + e.Message);
}
}
Run Code Online (Sandbox Code Playgroud)
它有效.该代码的功能如预期,我能提取从信息camInfoDICT的钥匙和价值观.
该问题是,它抛出一个Exception的Exception Array index is out of range.在
foreach (var item in items)
{
try
{
camInfoDICT.Add(item[0], item[1]);
}
catch (Exception e)
{
Debug.Log("Exception " + e.Message);
}
}
Run Code Online (Sandbox Code Playgroud)
我哪里做错了?
而不是手动解析,使用Json转换.该字符串是一个JSON字符串.您可以使用任何可用的JSON反序列化器,例如使用Newtonsoft JSON解析器,它将是:
string jsonString = "{\"error\":0,\"session\":678939290,\"group\":131071}";
Dictionary<string, int> camInfoDICT = JsonConvert.DeserializeObject<Dictionary<string, int>>(jsonString);
Run Code Online (Sandbox Code Playgroud)
要包含Netwonsoft JSON,请在Visual Studio中使用Nugget Package Manager.