Reputation: 125435
I am trying to split a response (string) received from a camera into keys and values. This is what the string from IP camera look like:
{"error":0,"session":678939290,"group":131071}
I want to Split them into keys and arrays without the "". For ecample:
Keys <---- >Values
error 0
session 678939290
group 131071
Below is the code I currently use:
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);
}
}
It works. The code functions as expected and I was able to extract the information from camInfoDICT
as Keys and Values.
The problem is that it is throwing an Exception
of Exception Array index is out of range
. in
foreach (var item in items)
{
try
{
camInfoDICT.Add(item[0], item[1]);
}
catch (Exception e)
{
Debug.Log("Exception " + e.Message);
}
}
Where did I go wrong?
Upvotes: 0
Views: 778
Reputation: 223322
Instead of doing manual parsing, use Json convert. The string is a JSON string. You can use any available JSON deserializers, for example with Newtonsoft JSON parser it would be:
string jsonString = "{\"error\":0,\"session\":678939290,\"group\":131071}";
Dictionary<string, int> camInfoDICT = JsonConvert.DeserializeObject<Dictionary<string, int>>(jsonString);
To include Netwonsoft JSON, use Nugget Package Manager in Visual Studio.
Upvotes: 7