0

I am making an API call. On successful completion I know the structure of JSON response. I can read that and save it on DB using JSON.NET, but if the API calls generates error, a JSON of unknown structure is generated. I have to parse and save it in DB. How can I do that.
In genral structure of error response is this:

{"origin-of_error":"error_message"} 

There are some cases though where additional key value is also present.

2
  • Has the unknown json-object always the structure origin : error like { foo : bar } or could it be { foo : bar, zuu : xaa } as well? Commented Jan 12, 2014 at 7:50
  • @threeFourOneSixOneThree Yes it is always like {foo:bar} but sometimes additionally it gives {foo: bar, koo:kaa} structure Commented Jan 12, 2014 at 7:51

2 Answers 2

3

Since you don't know the exact contents of the JSON, but you at least know it is a flat object with key-value pairs, then I would recommend deserializing into a Dictionary<string, string>. You can then easily iterate over the key-value pairs to extract the data you need to store in the DB.

string json = @" { ""origin-of_error"" : ""error_message"", ""foo"" : ""bar"" }"; var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json); foreach (KeyValuePair<string, string> kvp in dict) { Console.WriteLine(kvp.Key + ": " + kvp.Value); } 
Sign up to request clarification or add additional context in comments.

Comments

0

try this

IDictionary<string, JToken> jsondata = JObject.Parse(json); foreach (KeyValuePair<string, JToken> innerData in jsondata) { Console.WriteLine("{0}=> {1}",innerData.Key, innerData.Value.ToString()); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.