What I have is this:
string json = @"{'number': 3, 'object' : { 't' : 3, 'whatever' : 'hi', 'str': 'test'}";
How do I read the fields until I'm at 'object', then serialize the whole 'object' into a .NET type and then continue parsing?
What I have is this:
string json = @"{'number': 3, 'object' : { 't' : 3, 'whatever' : 'hi', 'str': 'test'}";
How do I read the fields until I'm at 'object', then serialize the whole 'object' into a .NET type and then continue parsing?
Define your types:
public class Object
{
public int t { get; set; }
public string whatever { get; set; }
public string str { get; set; }
}
public class RootObject
{
public int number { get; set; }
public Object object { get; set; }
}
Then just deserialize it:
string json = @"{'number': 3, 'object' : { 't' : 3, 'whatever' : 'hi', 'str': 'test'}";
var deserialized = JsonConvert.DeserializeObject<RootObject>(json);
//do what you want
UPDATE
You didn't say it's dynamic, for such parsing there is many solutions.
Check the following:
Using JSON.NET for dynamic JSON parsing
Using C# 4.0 and dynamic to parse JSON
Deserialize JSON into C# dynamic object?
Parse JSON block with dynamic variables
Turning JSON into a ExpandoObject
To handle a dynamic type: use dynamic
, to handle dynamic data such as XML or JSON use ExpandoObject
.
UPDATE 2
Using Anonymous types to deserialize JSON data
UPDATE 3
Will this work for you:
string json = "{\"number\": 3, \"object\" : { \"t\" : 3, \"whatever\" : \"hi\", \"str\": \"test\"}}";
var deserialized = SimpleJson.DeserializeObject<IDictionary<string, object>>(json);
var yourObject = deserialized["object"] as IDictionary<string, object>;
if (yourObject != null)
{
var tValue = yourObject.GetValue("t");
var whateverValue = yourObject.GetValue("whatever");
var strValue = yourObject.GetValue("str");
}
public static object GetValue(this IDictionary<string,object> yourObject, string propertyName)
{
return yourObject.FirstOrDefault(p => p.Key == propertyName).Value;
}
Final result:
Or change to the following
if (yourObject != null)
{
foreach (string key in yourObject.Keys)
{
var myValue = yourObject.GetValue(key);
}
}
UPDATE 4 - SERVICE STACK
string json = "{\"number\": 3, \"object\" : { \"t\" : 3, \"whatever\" : \"hi\", \"str\": \"test\"}}";
var deserialized = JsonObject.Parse(json);
var yourObject = deserialized.Get<IDictionary<string, object>>("object");
if (yourObject != null)
{
foreach (string key in yourObject.Keys)
{
var myValue = yourObject.GetValue(key);
}
}
Result:
Look at ServiceStack's Dynamic JSON Parsing:
var myPoco = JsonObject.Parse(json)
.GetUnescpaed("object")
.FromJson<TMyPoco>();
This works for deserializing, I will update once I got serializing.
foreach(KeyValuePair<String,String> entry in JsonObject.Parse(json))
{
}
Edit: Looks like this only works for json objects. I still don't know how to iterate over JsonArrayObjects