I am using JSON.NET to parse some JSON returned by my server. I feel kind of dumb, because I feel like I'm trying to do something simple. Yet, the code doesn't work. Currently, I'm getting some JSON bck from the server that looks like this:
[
{ id:'1', description:'Some kind of description' },
{ id:'2', description:'Another description' },
{ id:'3', description:'Here is another' }
]
Currently, I'm trying to take this JSON in C# and convert it to a Dictionary<string, string>
. My (failing) attempt looks like this:
private Dictionary<string, string> ParseResults(string json)
{
Dictionary<string, string> dictionary = new Dictionary<string, string>();
string descriptionPropertyName = "description";
string descriptionPropertyValue = null;
bool isDescriptionProperty = false;
string idPropertyName = "id";
string idPropertyValue = null;
bool isIdProperty = false;
JsonTextReader jsonReader = new JsonTextReader(new StringReader(json));
while (jsonReader.Read())
{
if (jsonReader.TokenType == JsonToken.PropertyName)
{
if (descriptionPropertyName.Equals(jsonReader.Value))
{
isDescriptionProperty = true;
}
else if (idPropertyName.Equals(jsonReader.Value))
{
isIdProperty = true;
}
}
else
{
if ((isDescriptionProperty == true) && (descriptionPropertyValue == null))
{
if (jsonReader.TokenType == JsonToken.String)
{
if (jsonReader.Value != null)
{
descriptionPropertyValue = jsonReader.Value.ToString();
}
}
}
else if ((isIdProperty == true) && (idPropertyValue == null))
{
if (jsonReader.TokenType == JsonToken.String)
{
if (jsonReader.Value != null)
{
idPropertyValue = jsonReader.Value.ToString();
}
}
}
}
if ((isDescriptionProperty == true) && (isIdProperty == true) && (descriptionPropertyValue != null) && (idPropertyValue != null))
{
dictionary.Add(idPropertyValue, descriptionPropertyValue);
}
}
return dictionary;
}
That's a lot of code for something that seems so simple. I feel I have to do something wrong. In fact, its not working, so something has to be wrong. I just can't determine what.
Thank you for any help you may be able to provide. Please remember, this is based on the .NET 2.0 framework.