Adding JObject to JArray - c#

Im trying to add a new class called "Company" to a Json Array called Companies. I'm doing this using C# and Json .net Ive tried many different things. I have them all pares out and in Jobjects ready to be molded together but I can't find a way to do so. Im trying to get it to find "Companies" then insert the new company object in there.
This is what im trying to do.
public void CreateNewCompany()
{
Company company = new Company
{
CompanyName = textBox1.Text,
IPO = Convert.ToDouble(textBox2.Text),
Category = CategorycomboBox1.SelectedItem.ToString(),
Description = textBox4.Text,
StartDate = Convert.ToInt32(textBox5.Text)
};
AddProductListItemsToFinishedJSON(company);
AddNewsArticlesListItemsToFinishedJSON(company);
JObject newCompany = JObject.FromObject(company);
string existingFileContents = File.ReadAllText(path);
string newFileContents = newCompany.ToString();
var existingFileContentsToJSON = JObject.Parse(existingFileContents);
var newFileContentsToJSON = JObject.Parse(newFileContents);
Debug.WriteLine(existingFileContents);
SaveJSONFile(company);
}
public void SaveJSONFile(Company localcompany)
{
if (File.Exists(Path.Combine(#"D:\", "comp.json")))
{
File.Delete(Path.Combine(#"D:\", "comp.json"));
}
string RawJSON = JsonConvert.SerializeObject(localcompany);
string FormattedJSON = JToken.Parse(RawJSON).ToString(Formatting.Indented);
//Console.WriteLine(FormattedJSON);
File.WriteAllText(#"D:\comp.json", FormattedJSON);
}
These are the classes
public class Company
{
public string CompanyName { get; set; }
public double IPO { get; set; }
public string Category { get; set; }
public string Description { get; set; }
public int StartDate { get; set; }
public List<Product> Products = new List<Product>();
public List<NewsArticle> CompanySpecificNewsArticles = new List<NewsArticle>();
public List<string> EavesDropperList = new List<string>();
}
public class Product
{
[JsonProperty("ProductName")]
public string ProductName { get; set; }
}
public class NewsArticle
{
[JsonProperty("Type")]
public string Type { get; set; }
[JsonProperty("Content")]
public string Content { get; set; }
}
This is what the Json Looks like and I want to add it to 'Companies'
{
"Companies":[
{
"CompanyName":"",
"IPO":25.0,
"Category":"Gaming",
"Description":"A video game company",
"StartDate":"1-1-2000",
"Products":[
{
"ProductName":""
},
{
"ProductName":""
}
],
"CompanySpecificNewsArticles":[
{
"Type":"Positive",
"Content":"This company has had a very good year!"
},
{
"Type":"Negative",
"Content":"This company has had a very bad year!"
},
{
"Type":"Neutral",
"Content":"This company is doing okay, I guess"
}
],
"CompanySpecificEavesdropper":[
{
"Type":"Positive",
"Content":"This company has had a very good year!"
},
{
"Type":"Negative",
"Content":"This company has had a very bad year!"
},
{
"Type":"Neutral",
"Content":"This company is doing okay, I guess!"
}
]
}
//,
// Other companies omitted
]
}

A JSON file is just a text file, so there's no straightforward way to insert a record into the middle of the file. Instead, you will need to load the entire file into some in-memory representation, add your Company to the "Companies" array, then re-serialize the file back to disk.
To accomplish this, first create the following extension methods:
public class JsonExtensions
{
public static T LoadFromFileOrCreateDefault<T>(string path, JsonSerializerSettings settings = null) where T : new()
{
var serializer = JsonSerializer.CreateDefault(settings);
try
{
using (var file = File.OpenText(path))
{
return (T)JsonSerializer.CreateDefault(settings).Deserialize(file, typeof(T));
}
}
catch (FileNotFoundException)
{
return new T();
}
}
public static void SaveToFile<T>(T root, string path, Formatting formatting = Formatting.None, JsonSerializerSettings settings = null)
{
using (var file = File.CreateText(path))
using (var writer = new JsonTextWriter(file) { Formatting = formatting })
{
JsonSerializer.CreateDefault(settings).Serialize(writer, root);
}
}
}
Now you can add your Company to the array in CreateNewCompany() as follows:
var root = JsonExtensions.LoadFromFileOrCreateDefault<JObject>(Path);
var companiesArray = (JArray)root["Companies"] ?? (JArray)(root["Companies"] = new JArray());
companiesArray.Add(JObject.FromObject(company));
JsonExtensions.SaveToFile(root, Path, Formatting.Indented);
Demo fiddle #1 here.
Incidentally, since your entire file seems to have a fixed schema, you could simplify your code and get slightly better performance by deserializing directly to some root data model, omitting the JObject representation entirely.
First, create the following root data model:
public class CompanyList
{
public List<Company> Companies { get; } = new List<Company>();
}
Then modify CreateNewCompany() as follows:
var root = JsonExtensions.LoadFromFileOrCreateDefault<CompanyList>(Path);
root.Companies.Add(company);
JsonExtensions.SaveToFile(root, Path, Formatting.Indented);
Demo fiddle #2 here.
Notes:
By using generics in JsonExtensions we can use the same code to load from, and save to, a file, for both JObject and CompanyList.
Serializing directly from and to your file without loading to an intermediate string should improve performance as explained in Performance Tips: Optimize Memory Usage.
Company.StartDate is declared to be an int, however in your JSON it appears as a non-numeric string:
"StartDate": "1-1-2000"
You will need to adjust your data model to account for this.
There is no need to manually delete the old file as File.CreateText(String) creates or opens a file for writing UTF-8 encoded text. If the file already exists, its contents are overwritten.
Alternatively you might want to write to a temporary file and then overwrite the old file only after serialization finishes successfully.
It is better to catch the FileNotFoundException from File.OpenText() rather than checking File.Exists() manually in case the file is somehow deleted in between the two calls.

This should give you an idea of what you should be doing
public void CreateNewCompany()
{
Company company = new Company
{
CompanyName = "New Company",
IPO = Convert.ToDouble("0.2"),
Category = "Sample Category",
Description = "Sample Description",
StartDate = Convert.ToInt32("2009")
};
AddProductListItemsToFinishedJSON(company);
AddNewsArticlesListItemsToFinishedJSON(company);
SaveJSONFile(company);
}
public static void SaveJSONFile(Company localcompany)
{
if (File.Exists(path))
{
JObject arr = JObject.Parse(File.ReadAllText(path)));
(arr["Companies"] as JArray).Add(JToken.FromObject(localcompany));
string RawJSON = JsonConvert.SerializeObject(arr);
string FormattedJSON = JToken.Parse(RawJSON).ToString(Formatting.Indented);
File.WriteAllText(path, FormattedJSON);
}
else
{
JObject arr = new JObject();
arr.Add("Companies", new JArray());
(arr["Companies"] as JArray).Add(JToken.FromObject(localcompany));
string RawJSON = JsonConvert.SerializeObject(arr);
string FormattedJSON = JToken.Parse(RawJSON).ToString(Formatting.Indented);
File.WriteAllText(path, FormattedJSON);
}
}
Delete your existing json file then run this code. The first run creates the file with one object while subsequent runs adds object to it. You can refactor the code.
Json file will have the format below
{
"Companies": [
{
"Products": [],
"CompanySpecificNewsArticles": [],
"EavesDropperList": [],
"CompanyName": "New Company",
"IPO": 0.2,
"Category": "Sample Category",
"Description": "Sample Description",
"StartDate": 2009
},
{
"Products": [],
"CompanySpecificNewsArticles": [],
"EavesDropperList": [],
"CompanyName": "New Company",
"IPO": 0.2,
"Category": "Sample Category",
"Description": "Sample Description",
"StartDate": 2009
}
]
}
as per your comment on the order, you can set order on you class like below
public class Company
{
[JsonProperty(Order = 0)]
public string CompanyName { get; set; }
[JsonProperty(Order = 1)]
public double IPO { get; set; }
[JsonProperty(Order = 2)]
public string Category { get; set; }
[JsonProperty(Order = 3)]
public string Description { get; set; }
[JsonProperty(Order = 4)]
public int StartDate { get; set; }
[JsonProperty(Order = 5)]
public List<Product> Products = new List<Product>();
[JsonProperty(Order = 6)]
public List<NewsArticle> CompanySpecificNewsArticles = new List<NewsArticle>();
[JsonProperty(Order = 7)]
public List<string> EavesDropperList = new List<string>();
}

Related

How to access multiple groups of nested JSON elements in C#?

I have a JSON being received from a public API that follows the structure below.
[
{
"ID": "12345",
"company": [
{
"contract_ID": "abc5678",
"company": [
{
"company_name": "HelloWorld",
"company_logo": "HW",
"invested": "2000"
}
]
},
{
"contract_ID": "67891",
"company": [
{
"company_name": "GoodBye",
"company_logo": "GB",
"invested": "500"
}
]
},
{
"contract_ID": "32658",
"company": [
{
"company_name": "YesNo",
"company_logo": "YN",
"invested": "1500"
}
]
}
]
}
]
I've tried several different methods of parsing, whether it be JTokens/JArrays or various classes. Something like the following allows me to access the first group of values (company_name, company_logo, invested), but I cannot iterate through to find the other two.
//receiving the json data
var responseString = await response.Content.ReadAsStringAsync();
var fullJSON = JsonConvert.DeserializeObject(responseString);
Debug.Log(fullJSON);
//trying to parse it down to just the data I need
JToken token = JToken.Parse("{\"root\":" + responseString + "}");
Debug.Log(token);
JArray assets = (JArray)token.SelectToken("root[0].assets");
Debug.Log(assets);
JToken dig = JToken.Parse("{\"root\":" + assets + "}");
Debug.Log(dig);
JArray assetsNested = (JArray)dig.SelectToken("root[0].assets");
Debug.Log(assetsNested);
My goal is to extract the contract_ID and then the associated company_name, company_logo, and invested items. For example, abc5678, HelloWorld, HW, and 2000 would be one of the three datasets needed.
The easiest way to deserialize this properly and keep your code maintainable is to use concrete classes. For example:
public sealed class Company
{
[JsonProperty("contract_ID")]
public string ContractID { get; set; }
[JsonProperty("company")]
public List<CompanyDefinition> CompanyDefinitions { get; set; }
}
public sealed class CompanyDefinition
{
[JsonProperty("company_name")]
public string CompanyName { get; set; }
[JsonProperty("company_logo")]
public string CompanyLogo { get; set; }
[JsonProperty("invested")]
public string Invested { get; set; }
}
public sealed class RootCompany
{
[JsonProperty("ID")]
public string ID { get; set; }
[JsonProperty("company")]
public List<Company> Company { get; set; }
}
Then, you simply deserialize. For example, if you are pulling from a file you could do this:
using(var sr = new StreamReader(#"c:\path\to\json.json"))
using(var jtr = new JsonTextReader(sr))
{
var result = new JsonSerializer().Deserialize<RootCompany[]>(jtr);
foreach(var r in result)
{
Console.WriteLine($"Company ID: {r.ID}");
foreach(var c in r.Company)
{
Console.WriteLine($"ContractID: {c.ContractID}");
foreach(var d in c.CompanyDefinitions)
{
Console.WriteLine($"Name: {d.CompanyName}");
Console.WriteLine($"Invested: {d.Invested}");
Console.WriteLine($"Company Logo: {d.CompanyLogo}");
}
}
}
}
When something changes with your models, you won't have to dig through lines upon lines of hard-to-read token selection code. You just update your models.

Convert csv file to json using C# with no header

I would like to convert CSV file to JSON using C#. I know that there are a lot of similar questions but I couldnĀ“t find something that could help me.
Source file looks like this:
2019-12-01T00:00:00.000Z;2019-12-10T23:59:59.999Z
50;false;2019-12-03T15:00:12.077Z;005033971003;48;141;2019-12-03T00:00:00.000Z;2019-12-03T23:59:59.999Z
100;false;2019-12-02T12:38:05.989Z;005740784001;80;311;2019-12-02T00:00:00.000Z;2019-12-02T23:59:59.999Z
First line is not header (actually I don't know how to call it - header usually have names of each property).
The result should look like this
{
"transactionsFrom": "2019-12-01T00:00:00.000Z","transactionsTo": "2019-12-10T23:59:59.999Z",
"transactions": [{
"logisticCode": "005033971003",
"siteId": "48",
"userId":"141",
"dateOfTransaction": "2019-12-03T15:00:12.077Z",
"price": 50
},
{
"logisticCode": "005729283002",
"siteId": "80",
"userId":"311",
"dateOfTransaction": "2019-12-02T12:38:05.989Z",
"price": 100
}]
}
I would like to use POCO - maybe something like this:
public class Headers
{
public string TransactionFrom { get; set; }
public string TransactionTo { get; set; }
}
public class Results
{
public string logisticCode { get; set; }
public string siteId { get; set; }
public string userId { get; set; }
public string dateOfTransaction { get; set; }
public string price { get; set; }
public string packSale { get; set; }
}
But the problem is I don't know how to continue. Maybe some example would help. I know I can use ChoETL, CsvHelper but I don't how.
This code might help you
Step1 - Create model class
public class Headers
{
public string TransactionFrom { get; set; }
public string TransactionTo { get; set; }
public List<Transaction> Transactions { get; set; }
}
public class Transaction
{
public string logisticCode { get; set; }
public string siteId { get; set; }
public string userId { get; set; }
public string dateOfTransaction { get; set; }
public string price { get; set; }
public string packSale { get; set; }
}
Step 2 - Split the file and read the records
string strInput = #"2019-12-01T00:00:00.000Z;2019-12-10T23:59:59.999Z
50;false;2019-12-03T15:00:12.077Z;005033971003;48;141;2019-12-03T00:00:00.000Z;2019-12-03T23:59:59.999Z
100;false;2019-12-02T12:38:05.989Z;005740784001;80;311;2019-12-02T00:00:00.000Z;2019-12-02T23:59:59.999Z";
var headers = new Headers();
var transactions = new List<Transaction>();
var csvrecords = strInput.Split(new[] { '\r', '\n' },StringSplitOptions.RemoveEmptyEntries);
int count = 1;
foreach(var record in csvrecords)
{
var values = record.Split(';');
if (count == 1)
{
headers.TransactionFrom = values[0];
headers.TransactionTo = values[1];
}
else
{
var transaction = new Transaction();
transaction.logisticCode = values[3].Trim();
transaction.siteId = values[4].Trim();
transaction.userId = values[5].Trim();
transaction.dateOfTransaction = values[2].Trim();
transaction.price = values[0].Trim();
transactions.Add(transaction);
}
count++;
}
headers.Transactions = transactions;
var jsonString = JsonConvert.SerializeObject(headers);
Console.WriteLine(jsonString);
Output -
{
"TransactionFrom": "2019-12-01T00:00:00.000Z",
"TransactionTo": "2019-12-10T23:59:59.999Z",
"Transactions": [
{
"logisticCode": "005033971003",
"siteId": "48",
"userId": "141",
"dateOfTransaction": "2019-12-03T15:00:12.077Z",
"price": "50",
"packSale": null
},
{
"logisticCode": "005740784001",
"siteId": "80",
"userId": "311",
"dateOfTransaction": "2019-12-02T12:38:05.989Z",
"price": "100",
"packSale": null
}
]
}
With Cinchoo ETL, you can do it as follows
Define class structures as below
public class Headers
{
public string TransactionFrom { get; set; }
public string TransactionTo { get; set; }
public List<Transaction1> Transactions { get; set; }
}
public class Transaction
{
[ChoFieldPosition(4)]
public string logisticCode { get; set; }
[ChoFieldPosition(5)]
public string siteId { get; set; }
[ChoFieldPosition(6)]
public string userId { get; set; }
[ChoFieldPosition(2)]
public string dateOfTransaction { get; set; }
[ChoFieldPosition(1)]
public string price { get; set; }
}
Parse the CSV, generate JSON as below
string csv = #"2019-12-01T00:00:00.000Z;2019-12-10T23:59:59.999Z
50;false;2019-12-03T15:00:12.077Z;005033971003;48;141;2019-12-03T00:00:00.000Z;2019-12-03T23:59:59.999Z
100;false;2019-12-02T12:38:05.989Z;005740784001;80;311;2019-12-02T00:00:00.000Z;2019-12-02T23:59:59.999Z";
string csvSeparator = ";";
using (var r = ChoCSVReader.LoadText(csv)
.WithDelimiter(csvSeparator)
.ThrowAndStopOnMissingField(false)
.WithCustomRecordSelector(o =>
{
string line = ((Tuple<long, string>)o).Item2;
if (line.SplitNTrim(csvSeparator).Length == 2)
return typeof(Headers);
else
return typeof(Transaction);
})
)
{
var json = ChoJSONWriter.ToTextAll(r.GroupWhile(r1 => r1.GetType() != typeof(Headers))
.Select(g =>
{
Headers master = (Headers)g.First();
master.Transactions = g.Skip(1).Cast<Transaction1>().ToList();
return master;
}));
Console.WriteLine(json);
}
JSON Output:
[
{
"TransactionFrom": "2019-12-01T00:00:00.000Z",
"TransactionTo": "2019-12-10T23:59:59.999Z",
"Transactions": [
{
"logisticCode": "005033971003",
"siteId": "48",
"userId": "141",
"dateOfTransaction": "false",
"price": "50"
}
{
"logisticCode": "005740784001",
"siteId": "80",
"userId": "311",
"dateOfTransaction": "false",
"price": "100"
}
]
}
]
I am not sure if i can help you with any codes as your source CSV is very confusing, but i'll try to give you some ideas that might work out.
Firstly, you don't need a model class. I mean, you can use it if you want, but seems unnecessary here.
Next up is reading the CSV file. As you haven't posted any codes related to that and also didn't mention any problem with reading the file, i assume you are reading the file properly. Reading the CSV and writing a JSON from it is relatively easy. However, the CSV file itself looks very confusing. How are you reading it tho? Are you reading it as plain text? Do you have column headers or atleast columns?
If you are reading the file as plain text, then i guess you only have one way. And that is splitting the string and construct a new string with the splitted values. Splitting should be relatively easy as you have ;(semi-colon) which is separating each column/data. So the basic idea is splitting the string and storing it in an array or list, something like this :
string[] values = myCSV.split(";");
Now all you need to do is, simply use the strings inside values to construct a new string. You can use the StringBuilder for that, or an easy way(not feasible tho) would be string concatenation. I personally would recommend you to go with the StringBuilder.
Guidelines:
StringBuilder in C#
Creating a new line in StringBuilder
Double quotes inside string
Hopefully this gives you some ideas.

c# Converting json string with list of objects to a c# object

I'm tring to convert a string json to c# object,
I've already read several replies in here regarding to similar questions but none of the solutions worked.
This is the json obj
{
"Customer": {
"data_0": {
"id": "273714",
"FirstName": "Zuzana",
"LastName": "Martinkova"
},
"data_1": {
"id": "274581",
"FirstName": "Ricardo",
"LastName": "Lambrechts"
},
"data_2": {
"id": "275190",
"FirstName": "Daniel",
"LastName": "Mojapelo"
},
"data_3": {
"id": "278031",
"FirstName": "Sulochana",
"LastName": "Chandran"
}
}
}
I created the following objects according to the json obj
public class Customer
{
public List<Data> Customers{ get; set; }
public Customer()
{
Customers = new List<Data>();
}
}
public class Data
{
public string id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
As for my code I made a small console app example with all the solotions I found here
static void Main(string[] args)
{
try
{
string jsonString = File.ReadAllText(ConfigurationSettings.AppSettings["filepath"].ToString());
//solution 1
JObject jsonone = JObject.Parse(jsonString);
var collection_one = jsonone.ToObject<Customer>();
//solution 2
JavaScriptSerializer serializer = new JavaScriptSerializer();
var collection_two = serializer.Deserialize<Customer>(jsonString);
//solution 2
var collection_three = JsonConvert.DeserializeObject<Customer> (jsonString);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message); ;
}
Console.ReadKey();
}
Ths json string I get from a 3rd party webservice so just for the example I'm reading the json from a txt file,
the jsonString param value after reading is:
"{\"Customer\":{\"data_0\":{\"id\":\"273714\",\"FirstName\":\"Zuzana\",\"LastName\":\"Martinkova\"},\"data_1\":{\"id\":\"274581\",\"FirstName\":\"Ricardo\",\"LastName\":\"Lambrechts\"},\"data_2\":{\"id\":\"275190\",\"FirstName\":\"Daniel\",\"LastName\":\"Mojapelo\"},\"data_3\":{\"id\":\"278031\",\"FirstName\":\"Sulochana\",\"LastName\":\"Chandran\"}}}"
On every solution I make the collections count is 0, data objects are not including inside the list.
Can someone put some light on it and tell me what is wrong?
Thanks in advance
Your JSON is a Dictionary<string, Data>, not a List<Data>. In addition to that your property is called "Customer", not "Customers". To solve this you need to change a couple things:
public class Customer
{
//JsonProperty is Used to serialize as a different property then your property name
[JsonProperty(PropertyName = "Customer")]
public Dictionary<string, Data> CustomerDictionary { get; set; }
}
public class Data
{
public string Id { get; set; } //You should make this "Id" not "id"
public string FirstName { get; set; }
public string LastName { get; set; }
}
With these class definitions you can easily use the JsonConvert.DeserializeObject() and JsonConvert.SerializeObject() methods:
Customer customer = JsonConvert.DeserializeObject<Customer>(json);
string newJson = JsonConvert.SerializeObject(customer);
I made a fiddle here to demonstrate.
You can try this one.
Add empty class
public class Customer : Dictionary<string, Data>{} //empty class
And the update your existing code
//solution 1
JObject jsonone = JObject.Parse(jsonString);
//Add this line
var token = jsonone.SelectToken("Customer").ToString();
//solution 2 - update jsonString to token variable created above.
var collection_three = JsonConvert.DeserializeObject<Customer>(token);

Json parse sub-collection in c#

How can I do JSON in C# like the data below ?
{
"Aliases": [ "teddy", "freddy", "eddy", "Betty" ],
"Name":"reacher gilt",
"Address":"100 East Way",
"Age":74,
"Bars": {
"items": [
{
"Sub_Property1":"beep",
"Sub_Property2":"boop"
},
{
"Sub_Property1":"meep",
"Sub_Property2":"moop"
},
{
"Sub_Property1":"feep",
"Sub_Property2":"foop"
}
]
}
}
Actually my problem is inside the sub-collection. I saw someone did something
like this
person.Bars.Add("items",
new List<BarClass>(new[]{
new BarClass("beep","boop"),
new BarClass("meep","moop"),
new BarClass("feep","foop"),
}));
So, I have to add new BarClass("beep","boop"), but I need to do something
like this
String [] no1 = {1,2,3}
String [] no2 = {4,5,6}
person.Bars.Add("items",
new List<BarClass>(new[]{
for ()
{
new BarClass(no1[i],no2[i])
}
}));
How can i do this? Thanks and please help..
To read the JSON
The best way to read the whole JSON is to Deserialize it to a native C# object. If you do not already have the classes with your, you can create it in Visual Studio as
Copy your JSON text
Create a new empty class file in VS
Edit > Paste Special > Paste JSON As Classes
Here are the classes
public class Person
{
public string[] Aliases { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public int Age { get; set; }
public Bars Bars { get; set; }
}
public class Bars
{
public Item[] items { get; set; }
}
public class Item
{
public string Sub_Property1 { get; set; }
public string Sub_Property2 { get; set; }
}
Now you can use some .NET JSON library to deserialize. JSON.Net aka Newtonsoft JSON is a great library. You get get it from NuGet as well.
Then it's pretty easy to get the C# object from the JSON
//using Newtonsoft.Json;
var jsonString = File.ReadAllText(#"C:\YourDirectory\person.json");
var person = JsonConvert.DeserializeObject<Person>(jsonString);
If you want to read the sub-collection only, you can rather use Linq-to-JSON to read the items directly, like this
//using Newtonsoft.Json.Linq;
var jObject = JObject.Parse(jsonString);
List<Item> details = jObject["Bars"]["items"].ToObject<List<Item>>();
To create the JSON
You first need to create the object, then Serialize to JSON
string[] subProperties1 = new string[] { "1", "2", "3" };
string[] subProperties2 = new string[] { "4", "5", "6" };
Person person = new Person { Name = "Johny", Age = 7, Address = "Earth", Aliases = new string[] { "Sony", "Monty" } };
person.Bars = new Bars {
items = subProperties1.Zip(subProperties2,
(prop1, prop2) => new Item { Sub_Property1 = prop1, Sub_Property2 = prop2 })
.ToArray() };
var json = JsonConvert.SerializeObject(person);
To create the items from your existing string arrays, I have used IEnumerable.Zip function from Linq. You can read about them here.
This is the created JSON data
{
"Aliases": [ "Sony", "Monty" ],
"Name": "Johny",
"Address": "Earth",
"Age": 7,
"Bars": {
"items": [
{
"Sub_Property1": "1",
"Sub_Property2": "4"
},
{
"Sub_Property1": "2",
"Sub_Property2": "5"
},
{
"Sub_Property1": "3",
"Sub_Property2": "6"
}
]
}
}
You should create some classes
public class Person
{
public string Name {get;set;}
public string Address{get;set;}
public int Age {get;set;}
public Header {get;set;}
}
public class Header
{
public Detail[] Details {get;set;}
}
public class Detail
{
public string Sub1 {get;set;}
public string Sub2 {get;set;}
}
Create instance from Person class and initialize to instance after than
JavaScriptSerializer serializer =new JavaScriptSerializer();
var result=serializer.Serialize(instanceOfPerson);
"result" is json data
Assuming that you mean you want to create JSON string, you need to create those classes and use something like Newtonsoft JSON.net:
public class Item
{
public string Sub_Property1 { get; set; }
public string Sub_Property2 { get; set; }
}
public class Bars
{
public List<Item> items { get; set; }
}
public class Person
{
public List<string> Aliases { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public int Age { get; set; }
public Bars Bars { get; set; }
}
Please read the documentation here: http://www.newtonsoft.com/json/help/html/Introduction.htm

Parsing JSON using LINQ

Hello I am facing a very simple problem but it is not getting Solved. Here is my class design
public class Program
{
public string ProgramName { get; set; }
public string ProgramTime { get; set; }
public string ProgramDetails { get; set; }
}
public class Listing
{
public string ChannelName { get; set; }
public string NowShowing { get; set; }
public string NowShowingTime { get; set; }
public string NowShowingDescription { get; set; }
public string NowShowingPicture { get; set; }
public List<Program> Programs { get; set; }
}
public class RootObject
{
public string status { get; set; }
public string about { get; set; }
public List<Listing> listings { get; set; }
}
I am parsing using the following code.
JObject json = JsonConvert.DeserializeObject(e.Result) as JObject;
Listing ls = new Listing
{
ChannelName = (string)json["listings"].Children()["ChannelName"],
NowShowing = (string)json["listings"].Children()["NowShowing"],
Programs = new Program
{
ProgramName = (string)json["listings"]["Program"]["ProgramName"]
}
};
Help me solve my lame approach. My concerns are parsing the items correctly and also how to add them to the nested list "Programs". The second one is more crucial.
Sample Json input-
{
"listings": [
{
"ChannelName": "NTV BANGLA",
"NowShowing": "Ei Shomoy (R)",
"NowShowingTime": "12:10",
"NowShowingDescription": "Ei Shomoy is a daily talk show ........",
"Programs": [
{
"ProgramName": "Ainer Chokhe (R)",
"ProgramTime": "13:00",
"ProgramDetails": "Human Rights and law based program Ainer Chokhe,"
},
{
"ProgramName": "Shonkhobash",
"ProgramTime": "15:10",
"ProgramDetails": "Drama serial Shonkhobash, script by Bipasha Hayat and"
}
]
},
{
"ChannelName": "CHANNEL i",
"NowShowing": "Taroka Kothon (Live)",
"NowShowingTime": "12:30",
"NowShowingDescription": "City Cell Taroka Kothon Live is a talk show ",
"Programs": [
{
"ProgramName": "Channel i Top News",
"ProgramTime": "13:00",
"ProgramDetails": "Mutual Trust Bank top news (Shirsho Shongbad)"
},
{
"ProgramName": "Ebong Cinemar Gaan",
"ProgramTime": "13:10",
"ProgramDetails": "Ebong Cinemar Gaan, a musical show based on "
}
]
}
]
}
EDIT1
var customers = JsonConvert.DeserializeObject<RootObject>(e.Result);
Listing ls = new Listing
{
ChannelName = customers.listings.First().ChannelName,
NowShowing=customers.listings.First().NowShowing,
Programs=??
};
if e.Result is string with your JSON try this
var jss = new JavaScriptSerializer();
var o = jss.Deserialize<RootObject>(e.Result);
UPDATE
possibly you need something like this
var customers = JsonConvert.DeserializeObject<RootObject>(e.Result);
Listing ls = new Listing
{
ChannelName = customers.listings.First().ChannelName,
NowShowing=customers.listings.First().NowShowing,
Programs=customers.listings.First().Programs
};
UPDATE2
if you want based on existing you can try comething like this
var customers = JsonConvert.DeserializeObject<RootObject>(e.Result);
Listing ls = new Listing
{
ChannelName = customers.listings.First().ChannelName,
NowShowing=customers.listings.First().NowShowing,
Programs=customers.listings.First().Programs.Select(p=>new Program{
ProgramName=p.ProgramName,
ProgramTime=p.ProgramTime,
ProgramDetails = p.ProgramDetails
}).ToList()
};
UPDATE3
or if you whant simply random you can try something like this
var customers = JsonConvert.DeserializeObject<RootObject>(e.Result);
Listing ls = new Listing
{
ChannelName = customers.listings.First().ChannelName,
NowShowing=customers.listings.First().NowShowing,
Programs=Enumerable.Range(1,10).Select(p=>new Program{
ProgramName="generated name",
ProgramTime="generated time",
ProgramDetails = "generated details"
}).ToList()
};
Use DataContractJsonSerializer to parse json string in windows phone.
MemoryStream memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(e.Result));
DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(List<RootObject>));
RootObject itemDataList = dataContractJsonSerializer.ReadObject(memoryStream) as RootObject;
ChannelName = itemDataList.listings.First().ChannelName;

Categories

Resources