how get all elements of array in deserialize json c#? - c#

In C #, I have 5-6 days and I wanted to try to use the api one site.
I have deserialize JSON and here is the format
[
{
"uid": 1476402,
"first_name": "",
"last_name": "",
"domain": "sandrische",
"online": 1,
"user_id": 1476402
},
{
"uid": 3813182,
"first_name": "",
"last_name": "",
"domain": "id3813182",
"online": 0,
"user_id": 3813182
},
{
"uid": 12789624,
"first_name": "",
"last_name": "",
"domain": "id12789624",
"online": 0,
"user_id": 12789624
}]
there is a class
public class vkResponse
{
[JsonProperty(PropertyName = "uid")]
public int Id { get; set; }
[JsonProperty(PropertyName = "first_name")]
public string FirstName { get; set; }
[JsonProperty(PropertyName = "last_name")]
public string LastName { get; set; }
[JsonProperty(PropertyName = "photo_50")]
public Uri PhotoUri { get; set; }
[JsonProperty(PropertyName = "online")]
[JsonConverter(typeof(BoolConverter))]
public bool IsOnline { get; set; }
[JsonProperty(PropertyName = "lists")]
public List<int> Lists { get; set; }
}
public class BoolConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(((bool)value) ? 1 : 0);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return reader.Value.ToString() == "1";
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(bool);
}
}
I want to get id
var req = new HttpRequest();
string resp = req.Get("https://api.vk.com/method/friends.get?user_ids=1&fields=domain&access_token=" + GetToken()).ToString();
JObject o = JObject.Parse(resp);
JArray array = (JArray)o["response"];
vkResponse v = JsonConvert.DeserializeObject<vkResponse>(array.First().ToString());
richTextBox1.Text = v.Id.ToString();
But I get only the first ID, how to get all ID?
I think that the problem in this array.First().ToString() ? Please help or give an example.

var v = JsonConvert.DeserializeObject<IEnumerable<vkResponse>>(array.ToString());
var userids = v.Select(x=>x.id);

Your response is an array of vkResponse classes, so you could deserialize it as a c# array:
vkResponse[] vkResponses = JsonConvert.DeserializeObject<vkResponse[]>(array.ToString());
Once you have the array you can loop through and access the IDs of each element.
Pleaase , give me example how loop through and access the IDs of each elemen
OK, here's a way to do it using elementary c# looping constructs and arrays:
vkResponse[] vkResponses = JsonConvert.DeserializeObject<vkResponse[]>(array.ToString());
if (vkResponses == null)
throw new JsonException();
int [] ids = new int[vkResponses.Length];
for (int i = 0; i < vkResponses.Length; i++)
{
ids[i] = vkResponses[i].Id;
}
If you want to show the IDs as a comma-separated sequence of integers in the rich text box, you use the following method to generate the string:
public static string ExtractVkResponseIds(string vkResponseJson)
{
vkResponse[] vkResponses = JsonConvert.DeserializeObject<vkResponse[]>(vkResponseJson);
if (vkResponses == null)
throw new JsonException();
StringBuilder sb = new StringBuilder();
// Format the ids as a comma separated string.
foreach (var response in vkResponses)
{
if (sb.Length > 0)
sb.Append(System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator);
sb.Append(response.Id.ToString());
}
return sb.ToString();
}
and call it like:
var req = new HttpRequest();
string resp = req.Get("https://api.vk.com/method/friends.get?user_ids=1&fields=domain&access_token=" + GetToken()).ToString();
JObject o = JObject.Parse(resp);
JArray array = (JArray)o["response"];
string ids = ExtractVkResponseIds(array.ToString());
richTextBox1.Text = ids;
I used the localized ListSeparator, by the way, which might not be a comma in your language. You can change it to a literal comma if you want.
Your sample Json string is missing a closing bracket ("]"), by the way.

Related

C# Deserialize JSON array with multiple objects

I'm taking in a JSON that I do not control in the format of this sample:
{
"Transaction Information": [
{
"Type": "This is the Type"
},
{
"Action": "No"
},
{
"Owner": "Simpsons"
},
{
"Buyer/Broker": "Y"
},
{
"Compensation to Buyer": 3.0
}
]
}
I want to deserialize it to a class such as:
public class Transaction
{
[JsonProperty("Transaction Information")]
public TransactionInformation[] TransactionInformation { get; set; }
}
public partial class TransactionInformation
{
[JsonProperty("Type", NullValueHandling = NullValueHandling.Ignore)]
public string Type { get; set; }
[JsonProperty("Action", NullValueHandling = NullValueHandling.Ignore)]
public string Action { get; set; }
[JsonProperty("Owner", NullValueHandling = NullValueHandling.Ignore)]
public string Owner { get; set; }
[JsonProperty("Buyer/Broker", NullValueHandling = NullValueHandling.Ignore)]
public string BuyerBroker { get; set; }
[JsonProperty("Compensation to Buyer", NullValueHandling = NullValueHandling.Ignore)]
public long? CompensationToBuyer { get; set; }
}
using the code
var obj = JsonConvert.DeserializeObject<Transaction>(json);
However that gives me a Transaction.TransactionInformation object with 5 records each with all 5 elements with each record having all null values except for one of the 5 elements.
Is there a simple way to to return all 5 elements in one record?
Is there a simple way to to return all 5 elements in one record?
Sure -- Just put each property in a single record:
var finalRecord = new TransactionInformation
{
Type = obj.TransactionInformation.FirstOrDefault(x => !string.IsNullOrEmpty(x.Type))?.Type,
Action = obj.TransactionInformation.FirstOrDefault(x => !string.IsNullOrEmpty(x.Action))?.Action,
Owner = obj.TransactionInformation.FirstOrDefault(x => !string.IsNullOrEmpty(x.Owner))?.Owner,
BuyerBroker = obj.TransactionInformation.FirstOrDefault(x => !string.IsNullOrEmpty(x.BuyerBroker))?.BuyerBroker,
CompensationToBuyer = obj.TransactionInformation.FirstOrDefault(x => x.CompensationToBuyer.HasValue)?.CompensationToBuyer
};
That JSON data you are working with isn't in the most convenient format. In a perfect world it would look like this:
{
"Transaction Information": [{
"Type": "This is the Type",
"Action": "No",
"Owner": "Simpsons",
"Buyer/Broker": "Y",
"Compensation to Buyer": 3.0
}
]
}
Then what you were doing would have worked fine and you wouldn't have to do this last step to normalize the data.
You can create a custom JsonConverter that enables you to hook into the deserialization for the type:
public class TransactionConverter : JsonConverter<Transaction>
{
public override void WriteJson(JsonWriter writer, Transaction value, JsonSerializer serializer)
{
}
public override Transaction ReadJson(JsonReader reader, Type objectType, Transaction existingValue,
bool hasExistingValue, JsonSerializer serializer)
{
var rootChildren = JToken.ReadFrom(reader).First.Children();
var item = new TransactionInformation();
foreach (var child in rootChildren.Children())
{
item.Type ??= (string)child["Type"];
item.Action ??= (string) child["Action"];
item.BuyerBroker ??= (string)child["Buyer/Broker"];
item.Owner ??= (string)child["Owner"];
item.CompensationToBuyer ??= (long?)child["Compensation to Buyer"];
}
return new Transaction {TransactionInformation = new[] {item}};
}
public override bool CanRead => true;
}
and then call it:
var tx = JsonConvert.DeserializeObject<Transaction>(str, new TransactionConverter());

How to deserialize JSON with dynamic and static key names in C#

I have to deserialize a response from an api which has the following structure:
[
{
"starttime": "...",
"endtime": "....",
"var1": {},
"var2": {}
},
{
"starttime": "...",
"endtime": "....",
"var1": {},
"var3": {}
},
{
"starttime": "...",
"endtime": "....",
"var1": {}
}
]
Some insights:
The JSON is an array of objects
Every object inside the array will ALWAYS have the properties "starttime" and "endtime"
Objects "var1", "var2", "var3" will ALWAYS have the same properties inside them... but the problem is that the object keys (var1, var2 or var3) are dynamic. It can be any string, and also the amount of this kind of objects is dynamic (I could have 3, or zero "var" objects).
I was thinking something like this, to deserialize the JSON string into a List of objects with properties "starttime", "endtime" and a dictionary with all the "var" objects.
public class MyResponse
{
[JsonProperty(PropertyName = "starttime")]
public string StartTime { get; set; }
[JsonProperty(PropertyName = "endtime")]
public string EndTime { get; set; }
public Dictionary<string, VarObject> VarData { get; set; }
}
But the VarData property is always null.
Has anyone tried something like this?
You have two options, the first is to deserialise directly to a List<Dictionary<string, object>>, for example:
var responses = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(json);
Alternatively, if you are stuck on using your object, you will need to write a custom converter. For example, something like this:
public class MyResponseConverter : JsonConverter
{
public override bool CanConvert(Type type) => type == typeof(MyResponse);
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var responseObject = JObject.Load(reader);
MyResponse response = new MyResponse
{
StartTime = (string)responseObject["starttime"],
EndTime = (string)responseObject["endtime"],
};
var varData = new Dictionary<string, object>();
foreach (var property in responseObject.Properties())
{
if(property.Name == "starttime" || property.Name == "endtime")
{
continue;
}
varData.Add(property.Name, property.Value);
}
response.VarData = varData;
return response;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
// If you want to write to JSON, you will need to implement this method
throw new NotImplementedException();
}
}
And your class would change slightly to this:
[JsonConverter(typeof(MyResponseConverter))]
public class MyResponse
{
[JsonProperty(PropertyName = "starttime")]
public string StartTime { get; set; }
[JsonProperty(PropertyName = "endtime")]
public string EndTime { get; set; }
public Dictionary<string, object> VarData { get; set; }
}
Now you deserialise like this:
var responses = JsonConvert.DeserializeObject<List<MyResponse>>(json);
You can view example Here https://dotnetfiddle.net/QgXWQi.
But for more flexibility, this logic is better to implement in method that marked as [OnDeserialized]
Like here https://www.newtonsoft.com/json/help/html/SerializationAttributes.htm
The main idea is to parse it as JObject and then convert to Dictionary
var jObj = JObject.Parse(jsonText);
var varData = jObj
.Children<JProperty>()
.Where(p => p.Name != "starttime" && p.Name != "endtime")
.ToDictionary(x=> x.Name, x => ((JObject)x.Value).ToObject<VarObject>());

Print object with nested properties as string of comma separated key-value pairs

I have a Person class:
public class Person
{
public string Name { get; set; }
public string Surname { get; set; }
public Address Address { get; set; }
}
public class Address
{
public string Line1 { get; set; }
public string Line2 { get; set; }
}
As an end result, I would like to print out a Person instance as JSON, but I'd like it to be a huge string of key-value pairs, e.g.:
"Name:John,Surname:Doe,Line1:Infinite Loop,Line2:California"
Notice that in the example above, I got rid of the actual class names (i.e. it prints out Line1 instead of Address.Line1) - i only care about all the name/value pairs.
So the end result would be an array of Persons:
"persons":[
"Name:John,Surname:Doe,Line1:Infinite Loop 1,Line2:California",
"Name:Jane,Surname:Doe,Line1:Infinite Loop 2,Line2:California"
]
As a starting point, I tried using reflection:
void Main()
{
var persons = new List<Person>();
persons.Add(new Person
{
Name = "John",
Surname = "Doe",
Address = new Address
{
Line1 = "Infinite Loop",
Line2 = "California"
}
});
foreach(var person in persons)
{
var properties = new List<string>();
foreach(var property in person.GetType().GetProperties())
{
properties.Add($"{property.Name}:{property.GetValue(person, null)}");
}
Console.WriteLine(string.Join(",", properties));
}
}
But I get the following output in LINQPad:
Name:John,Surname:Doe,Address:UserQuery+Address
I assume Address is not properly iterated upon because it's a nested object within Person. Even so, this doesn't look like the most clean/efficient approach.
You could do this using a custom JsonConverter like so:
class PersonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Person);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
var pairs = JObject.FromObject(value)
.Descendants()
.OfType<JProperty>()
.Where(p => p.Value is JValue)
.Select(p => p.Name + ":" + p.Value);
writer.WriteValue(string.Join(",", pairs));
}
public override bool CanRead
{
get { return false; }
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
Then use it by passing the converter to JsonConvert.SerializeObject like this:
string json = JsonConvert.SerializeObject(obj, Formatting.Indented, new PersonConverter());
Here is a working demo: https://dotnetfiddle.net/L4YDsm
Add a ToString override to your class and return a collection of strings as JSON.
public class Person
{
public string Name { get; set; }
public string Surname { get; set; }
public Address Address { get; set; }
public override string ToString()
{
return $"Name:{Name},Surname:{Surname},Line1:{Address?.Line1},Line2:{Address?.Line2}";
}
}
You must implement the reflection in a way that it could go deeper into the structure of your object in order to do what you want. Here's a simple recursive and generic adaptation to your provided code.
public static string GetRecursivePropertyValues(object obj)
{
var properties = new List<string>();
foreach (var property in obj.GetType().GetProperties())
{
object currentPropertyValue = property.GetValue(obj);
if (property.PropertyType.IsPrimitive || property.PropertyType == typeof(string))
properties.Add($"{property.Name}:{currentPropertyValue}");
else
{
var subProperties = GetRecursivePropertyValues(currentPropertyValue);
properties.Add(subProperties);
}
}
return string.Join(";", properties);
}
This implementation first verifies if each property is defined with a primitive type or string (which are not considered primitive types in C#) and prints them normally if that's the case. Else, if the type is complex (like if it is declared as an Address instance), it recursivelly retrieves the properties of the complex object, and adds them to the resulting string.
You can call it like:
string propertiesStr = GetRecursivePropertyValues(person);
Edit: code now only flattens the object as required by OP (previous code sample used some rustic JSON formatting).
Using Newtonsoft.json
https://www.newtonsoft.com/json/help/html/SerializingJSON.htm
Check the above link... It will tell you how to serialize an object to json, it's important to note, you will want to add all your items to a list, then serialize the list into json to get the desired effect
Product product = new Product();
product.Name = "Apple";
product.ExpiryDate = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
There example:
string output = JsonConvert.SerializeObject(product);
//{
// "Name": "Apple",
// "ExpiryDate": "2008-12-28T00:00:00",
// "Price": 3.99,
// "Sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}

Convert DataSet with multiple Datatables to Json

I want to convert a dataset which has multiple data-tables within it.
Following is the example,
The dataset X has two data tables A and B
I want the result as follows,
{
"type":"A",
"value":"100",
"details":[
{"name":"John", "age":"45", "gender":"M"},
{"name":"Sebastin", "age":"34", "gender":"M"},
{"name":"Marc", "age":"23", "gender":"M"},
{"name":"Natalia", "age":"34", "gender":"F"}
]
}
Currently I am using Newtonsoft.Json. Is it possible with Newtonsoft.Json?
If not, is it possible with any other .net Json tools?
You can get the JSON you want by implementing a custom JsonConverter for the DataSet like this:
class CustomDataSetConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(DataSet));
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
DataSet x = (DataSet)value;
JObject jObject = new JObject();
DataTable a = x.Tables["A"];
foreach (DataColumn col in a.Columns)
{
jObject.Add(col.Caption.ToLower(), a.Rows[0][col].ToString());
}
JArray jArray = new JArray();
DataTable b = x.Tables["B"];
foreach (DataRow row in b.Rows)
{
JObject jo = new JObject();
foreach (DataColumn col in b.Columns)
{
jo.Add(col.Caption.ToLower(), row[col].ToString());
}
jArray.Add(jo);
}
jObject.Add("details", jArray);
jObject.WriteTo(writer);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
Here is a demo:
class Program
{
static void Main(string[] args)
{
DataSet x = new DataSet();
DataTable a = x.Tables.Add("A");
a.Columns.Add("Type");
a.Columns.Add("Value");
a.Rows.Add("A", "100");
DataTable b = x.Tables.Add("B");
b.Columns.Add("Name");
b.Columns.Add("Age");
b.Columns.Add("Gender");
b.Rows.Add("John", "45", "M");
b.Rows.Add("Sebastian", "34", "M");
b.Rows.Add("Marc", "23", "M");
b.Rows.Add("Natalia", "34", "F");
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.Converters.Add(new CustomDataSetConverter());
settings.Formatting = Formatting.Indented;
string json = JsonConvert.SerializeObject(x, settings);
Console.WriteLine(json);
}
}
Output:
{
"type": "A",
"value": "100",
"details": [
{
"name": "John",
"age": "45",
"gender": "M"
},
{
"name": "Sebastian",
"age": "34",
"gender": "M"
},
{
"name": "Marc",
"age": "23",
"gender": "M"
},
{
"name": "Natalia",
"age": "34",
"gender": "F"
}
]
}
I don't think Json.Net will do this automatically, but you should be able to do this using Typed Datasets.
A typed dataset is the same as the regular DataSet/DataTable classes, but they extend them with properties for each column in the tables and with relations.
Edit:
Alternatively you could build a method that converts the DataTable structures into a class model and then use Json.Net to serialize that. The data model would be simple, with only two classes, and the conversion should also be quite simple to implement.
Edit 2:
An example of how to convert the data table into a class structure:
public class ClassA
{
public string Type { get; set; }
public int Value { get; set; }
public List<ClassB> Details { get; set; }
public static ClassA FromDataRow(DataRow row, IEnumerable<DataRow> relatedRows)
{
var classA = new ClassA
{
Type = (string) row["Type"],
Value = (int) row["Value"],
Details = relatedRows.Select(r => new ClassB
{
Name = (string)r["Name"],
Age = (int)r["Age"],
Gender = (string)r["Gender"]
}).ToList()
};
return classA;
}
}
public class ClassB
{
public string Name { get; set; }
public int Age { get; set; }
public string Gender { get; set; }
}
Here you can run ClassA.FromDataRow() and pass it one row from TableA and a list of rows from TableB and end up with an object structure. This can easily be serialized to the format you want.
Please note that the code must be modified for your use and will probably not compile as it is. But the concept should be clear.
Final Solution for reference
using System.Web.Script.Serialization;
public class ClassA
{
public string Type { get; set; }
public string Value { get; set; }
public List<ClassB> Details { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
DataSet x = new DataSet();
DataTable a = x.Tables.Add("A");
a.Columns.Add("Type");
a.Columns.Add("Value");
a.Rows.Add("A", "100");
DataTable b = x.Tables.Add("B");
b.Columns.Add("Name");
b.Columns.Add("Age");
b.Columns.Add("Gender");
b.Rows.Add("John", "45", "M");
b.Rows.Add("Sebastian", "34", "M");
b.Rows.Add("Marc", "23", "M");
b.Rows.Add("Natalia", "34", "F");
var s = FromDataRow(a.Rows[0], b.AsEnumerable());
JavaScriptSerializer jss = new JavaScriptSerializer();
string output = jss.Serialize(s);
}
public static ClassA FromDataRow(DataRow row, IEnumerable<DataRow> relatedRows)
{
var classA = new ClassA
{
Type = (string)row["Type"],
Value = (string)row["Value"],
Details = relatedRows.Select(r => new ClassB
{
Name = (string)r["Name"],
Age = (string)r["Age"],
Gender = (string)r["Gender"]
}).ToList()
};
return classA;
}
}
public class ClassB
{
public string Name { get; set; }
public string Age { get; set; }
public string Gender { get; set; }
}
Here's a simplified answer:
var datasetList= new List();
var yourChanges= yourDataset.GetChanges();
datasetList.Add(yourChanges);
Once changes are added:
JsonConert.Serialize(datasetList, Formatting.Indented);
this will generated the json for all records.

JSON.net - field is either string or List<string>

I have a situation where the JSON returned from a REST-service returns a list of Movie-objects, all specced out with a ton of information. A couple of fields in that REST-service result changes depending on the information available.
An example: A Movie always has some screen captures (images), actors and directors. Depending on the movie in question, there might be one or more images, one or more actors and one or more directors. Sample JSON for a couple of cases:
{
"title": "Movie title",
"images": [
"http://www.url.com/img_0.jpg",
"http://www.url.com/img_1.jpg",
"http://www.url.com/img_2.jpg",
"http://www.url.com/img_3.jpg",
"http://www.url.com/img_4.jpg"
],
"actors": [
"Steven Berkoff",
"Nikolaj Coster-Waldau",
"Julie Cox"
],
"directors": "Simon Aeby"
},
{
"title": "Another movie",
"images": "http://www.url.com/img_1.jpg",
"actors": "actor 1"
"directors": [
"Justin Bieber",
"Justin Timberlake"
]
}
The question is, using JSON.net, how can I create a converter that deals with this problem? I've been scouring the internet, but still haven't found a solution.
Another spin on the same question: If a field is either a List of strings or a simple string, how do I make JSON.NET create a List either way (and if just a simple string, create a list with one member)
EDIT: This REST-service is out of my control
Ok, I did it for fun, but don't think is useful or the best way, anyway...
Declaring the "dynamic" attributes as object and then create methods to obtain the properties as something like ImagesAsList or ImagesAsString. I did it with Extension Methods.....
var movies = JsonConvert.DeserializeObject<List<Movie>>(str);
Class
class Movie
{
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("images")]
public object Images { get; set; }
[JsonProperty("actors")]
public object Actor { get; set; }
[JsonProperty("directors")]
public object Directors { get; set; }
}
Extension Methods
static class MovieExtension
{
public static List<string> ImagesAsList(this Movie m)
{
var jArray = (m.Images as JArray);
if (jArray == null) return null;
return jArray.Select(x => x.ToString()).ToList();
}
public static string ImagesAsString(this Movie m)
{
return m.Images as string;
}
}
EDIT
After reading #yamen comments I did some changes like:
var settings = new JsonSerializerSettings();
settings.Converters.Add(new MoviesConverter());
var movies = JsonConvert.DeserializeObject<List<Movie>>(str, settings);
Class
class Movie
{
[JsonProperty("title")]
public List<string> Title { get; set; }
[JsonProperty("images")]
public List<string> Images { get; set; }
[JsonProperty("actors")]
public List<string> Actor { get; set; }
[JsonProperty("directors")]
public List<string> Directors { get; set; }
}
Converter
class MoviesConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(string)) || (objectType == typeof(List<string>)) ;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.StartArray)
{
var l = new List<string>();
reader.Read();
while (reader.TokenType != JsonToken.EndArray)
{
l.Add(reader.Value as string);
reader.Read();
}
return l;
}
else
{
return new List<string> { reader.Value as string };
}
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
//ToDo here we can decide to write the json as
//if only has one attribute output as string if it has more output as list
}
}
You won't be able to serialise directly to an object, but you can do so manually without too much effort. JSON.Net contains LINQ to JSON. First define a method that will always return a list of type T even if the underlying JSON is not an array:
public List<T> getSingleOrArray<T>(JToken token)
{
if (token.HasValues)
{
return token.Select(m => m.ToObject<T>()).ToList();
}
else
{
return new List<T> { token.ToObject<T>() };
}
}
Sample usage:
JObject m1 = JObject.Parse(#"{
""title"": ""Movie title"",
""images"": [
""http://www.url.com/img_0.jpg"",
""http://www.url.com/img_1.jpg""
],
""actors"": [
""Steven Berkoff"",
""Julie Cox""
],
""directors"": ""Simon Aeby""
}");
JObject m2 = JObject.Parse(#"{
""title"": ""Another movie"",
""images"": ""http://www.url.com/img_1.jpg"",
""actors"": ""actor 1"",
""directors"": [
""Justin Bieber"",
""Justin Timberlake""
]
}");
IList<String> m1_directors = getSingleOrArray<string>(m1["directors"]);
IList<String> m2_directors = getSingleOrArray<string>(m2["directors"]);
m1_directory is a list with a single element, m2_directors is a list with two elements.

Categories

Resources