I have come across a problem, I need to basicly deserialize this:
<?xml version="1.0" encoding="UTF-8"?>
<api_data>
<status>ok</status>
<sessions>
<id>2</id>
<sessionID>6bfd1f1a7e87a8a6ed476234ad1d6e86</sessionID>
<gameID>1</gameID>
<maxPlayers>8</maxPlayers>
<hostIP>12.0.0.1</hostIP>
<hostPort>1993</hostPort>
<inProgress>0</inProgress>
<timestamp>1358894690</timestamp>
</sessions>
<sessions>
<id>3</id>
<sessionID>eeb4dc2df32f885c2b7d13f28a246830</sessionID>
<gameID>1</gameID>
<maxPlayers>8</maxPlayers>
<hostIP>12.0.0.1</hostIP>
<hostPort>1993</hostPort>
<inProgress>0</inProgress>
<timestamp>1358894732</timestamp>
</sessions>
</api_data>
And I need to convert that to usable data, its also dynamic, so there could be more than just 2 session elements, there could be 4, 20, or 0, the code I have now is just broken, and I was wondering whats a good method to get this to work?
Currently I am up to the point of the XDocument class, with all this loaded.
And I need to return a multi-dimensional array with this data.
EDIT:
Current code, completely broken:
var xmlSessions = xmlDATA.Descendants("api_data").Elements("sessions").Select(x => x);
result = new string[xmlDATA.Descendants("api_data").Count(), 7];
EDIT 2:
More info
The way I was thinking the MultiDimensional Array would be is as follows:
array[0,0] "ok" //Status
array[1,0 to 7] //First Session details go here
array[2,0 to 7] //Second session details go here, and so forth.
You can define the following class representations:
public class api_data
{
public string status { get; set; }
[XmlElement]
public session[] sessions { get; set; }
}
public class session
{
public int id { get; set; }
public string sessionID { get; set; }
public int gameID { get; set; }
public int maxPlayers { get; set; }
public string hostIP { get; set; }
public int hostPort { get; set; }
public int inProgress { get; set; }
public int timestamp { get; set; }
}
The key is the [XmlElement] tag on the sessions property, that will instruct the XmlSerializer to read/write XML using the schema sample you provided. To deserialize it, you can use the XmlSerializer as such:
//this might change, not sure how you obtain your xml,
//but let's assume you already have it available as a string
byte[] xmlBytes = System.Text.Encoding.UTF8.GetBytes(xmlData);
var stream = new MemoryStream(xmlBytes);
XmlSerializer serializer = new XmlSerializer(typeof(api_data));
api_data apidata = (api_data)serializer.Deserialize(stream);
Don't need any more XML adornment or setup than that to read it in (tested and working).
EDIT: Though you may want to consider using some other XML attributes to transfer to some nicer naming conventions, and we can also List<Session> to boot instead of an array:
[XmlRoot("api_data")]
public class ApiData
{
[XmlElement("status")]
public string Status { get; set; }
[XmlElement("sessions")]
public List<Session> Sessions { get; set; }
}
public class Session
{
[XmlElement("id")]
public int ID { get; set; }
[XmlElement("sessionID")]
public string SessionID { get; set; }
[XmlElement("gameID")]
public int GameID { get; set; }
[XmlElement("maxPlayers")]
public int MaxPlayers { get; set; }
[XmlElement("hostIP")]
public string HostIP { get; set; }
[XmlElement("hostPort")]
public int HostPort { get; set; }
[XmlElement("inProgress")]
public int InProgress { get; set; }
[XmlElement("timestamp")]
public int TimeStamp { get; set; }
}
EDIT: Just noticed that you need to turn this into a multidimensional array (not sure why, but you specify that's legacy). Well at this point, you have a nice object model from which you can do this data transfer. Not sure how you do the typing, but let's just assuming object type array for now:
ApiData apiData = DeserializeMyApiData(); // from above
array[0][0] = apiData.Status;
for(int i = 1; i <= apiData.Sessions.Count; i++)
{
var session = apiData.Sessions[i - 1];
array[i] = new object[8];
array[i][0] = session.ID;
array[i][1] = session.SessionID;
array[i][2] = session.GameID;
array[i][3] = session.MaxPlayers;
array[i][4] = session.HostIP;
array[i][5] = session.HostPort;
array[i][6] = session.InProgress;
array[i][7] = session.TimeStamp;
}
That will go through and build up your array regardless of how many sessions you have.
Can you wrap the 'sessions' tags inside a 'session_list' tag?
If so you could use something like this to load it:
public class api_data {
public class sessions {
public string id { get; set; }
public string sessionID { get; set; }
// put all the other vars in here ...
}
public string status { get; set; }
public List<sessions> session_list { get; set; }
public static api_data LoadFromXML(string xmlFile) {
api_data localApiData;
// serialize from file
try {
var xs = new XmlSerializer(typeof(api_data),
new XmlRootAttribute("api_data"));
using (TextReader tr = new StreamReader(xmlFile)) {
localApiData= xs.Deserialize(tr) as api_data;
}
}
catch (Exception ex) {
Log.LogError(string.Format(
"Error reading api_data file {0}: {1}",
xmlFile, ex.Message));
return null;
}
return localApiData;
}
}
If you cannot change the format of the xml file, you might need to load the status in it's own step and then load the sessions as if the api-data was the list variable, although the fact the status is there, might give you an error.
If you really only want a multidimensional array, you can obtain this from that XML with a single (somewhat long) line of code:
string[][] items = XDocument.Parse(xml).Root.Elements().Select(e => e.HasElements ? e.Elements().Select(ei => ei.Value).ToArray() : new string[]{ e.Value }).ToArray();
Or to make that same single statement a bit more readable:
string[][] items =
XDocument.Parse(xml).Root
.Elements().Select(e => e.HasElements ?
e.Elements().Select(ei => ei.Value).ToArray() : new string[]{ e.Value })
.ToArray();
From that source XML, this would produce an array like this:
string[][]
{
{ "ok" },
{ "2", "6bfd1f1a7e87a8a6ed476234ad1d6e86", "1", "8", "12.0.0.1", "1993", "0", "1358894690" },
{ "3", "eeb4dc2df32f885c2b7d13f28a246830", "1", "8", "12.0.0.1", "1993", "0", "1358894732" }
}
If you want to get the status separately, and put the other values in a multidimensional array, you could do this:
XDocument doc = XDocument.Parse(xml);
string status = doc.XPathSelectElement("/*/status").Value;
string[][] items =
doc.Root.Elements().Where(e => e.HasElements)
.Select(e => e.Elements().Select(ei => ei.Value).ToArray()).ToArray();
This would produce the same as above, except status would be an individual string, and items would not have the first single-element array in it:
string[][]
{
{ "2", "6bfd1f1a7e87a8a6ed476234ad1d6e86", "1", "8", "12.0.0.1", "1993", "0", "1358894690" },
{ "3", "eeb4dc2df32f885c2b7d13f28a246830", "1", "8", "12.0.0.1", "1993", "0", "1358894732" }
}
Related
I have a GameConsole model :
public class GameConsole
{
public int ID { get; protected set; } = 0;
public string Identifier { get; protected set; } = "GameConsole";
public List<string> ValidInputs { get; set; } = new List<string>(8);
public Dictionary<string, InputAxis> InputAxesMap { get; protected set; } = new Dictionary<string, InputAxis>(8);
public Dictionary<string, InputButton> InputButtonMap { get; protected set; } = new Dictionary<string, InputButton>(32);
public string ValidInputsStr { get; set; } = string.Empty;
public string InputAxesMapStr { get; set; } = string.Empty;
public string InputButtonMapStr { get; set; } = string.Empty;
}
I need ValidInputs, InputAxesMap, and InputButtonMap stored in an SQLite database. I've done this by serializing to JSON in their respective ValidInputsStr, InputAxesMapStr, and InputButtonMapStr fields.
However, I need to use these lists and dictionaries in the application. But each time I open the database context, ValidInputs, InputAxesMap, and InputButtonMap don't contain the data (unless I deserialize them from the JSON strings).
using (MyDatabaseContext context = new MyDatabaseContext(databasePath))
{
GameConsole gmConsole = context.Consoles.First((console) => console.Identifier == "GC");
Console.WriteLine(gmConsole.InputButtonMap.Count); //Prints 0
gmConsole.ReadInJSONFields(); //This is what I want to eliminate
Console.WriteLine(gmConsole.InputButtonMap.Count); //Has the proper data after reading from JSON
}
This is inconvenient considering there will be more objects in the future. How can I have everything be read and written directly to and from the database, and have these fields be populated?
An example GameConsole in JSON form:
{
"Identifier": "GC",
"ValidInputs": [
"left",
"up",
"a",
"b"
],
"InputAxesMap": {
"left": {
"AxisVal": 0,
"MinAxisVal": 0.0,
"MaxAxisVal": -1.0,
"MaxPercentPressed": 100
},
"up": {
"AxisVal": 1,
"MinAxisVal": 0.0,
"MaxAxisVal": -1.0,
"MaxPercentPressed": 100
},
"InputButtonMap": {
"a": {
"ButtonVal": 0
},
"b": {
"ButtonVal": 1
}
}
}
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.
I have a text file with below format data
[
{
"SponsorID": 1,
"FirstBAID": 7395836
},
{
"SponsorID": 2,
"FirstBAID": 3509279,
"SecondBAID": 2947210
},
{
"SponsorID": 3,
"FirstBAID": 1776294,
"SecondBAID": 6503843
},
{
"SponsorID": 4,
"FirstBAID": 8014528,
"SecondBAID": 6203155
},
{
"SponsorID": 5,
"FirstBAID": 5968769,
"SecondBAID": 7410195,
"ThirdBAID":8950170,
}
]
I want to read this data as a List & then i need to query by SponsorID.
I have created a class like this
public class SponsorInfo
{
public decimal SponsorID { get; set; }
public decimal FirstBAID { get; set; }
public decimal SecondBAID { get; set; }
public decimal ThirdBAID { get; set; }
}
Now how can i read text file data & bind SponsorInfo class ?
Install Newtonsoft.Json nuget package from NuGet package manager console:
PM> Install-Package Newtonsoft.Json
Then:
var jsonText = File.ReadAllText("filepath");
var sponsors = JsonConvert.DeserializeObject<IList<SponsorInfo>>(jsonText);
To query on SponsorID you can use LINQ:
var sponsor5 = sponsors.FirstOrDefault(x => x.SponsorID == 5);
If you often need a lookup by SponsorID, you could convert the result to a dictionary where the key is the SponsorID. This will improve performance as it doesn't need to enumerate through the entire list for each lookup. I also suggest you change the type of SponsorID to an int instead of a decimal.
var sponsorsById = sponsors.ToDictionary(x => x.SponsorID);
Then you can easily access it like:
if (sponsorsById.ContainsKey(5))
var sponsor5 = sponsorsById[5];
You need to install Newtonsoft.Json and then you need use it:
using Newtonsoft.Json;
class Program
{
public void LoadJson()
{
using (StreamReader r = new StreamReader("file.json"))
{
string json = r.ReadToEnd();
List<SponsorInfo> items = JsonConvert.DeserializeObject<List<SponsorInfo>>(json);
}
}
public class SponsorInfo
{
public decimal SponsorID { get; set; }
public decimal FirstBAID { get; set; }
public decimal SecondBAID { get; set; }
public decimal ThirdBAID { get; set; }
}
static void Main(string[] args)
{
dynamic array = JsonConvert.DeserializeObject(json);
foreach (var item in array)
{
Console.WriteLine("{0} {1}", item.temp, item.vcc);
}
}
}
Extend the class by creating a list object
public class SponsorInfo
{
public decimal SponsorID { get; set; }
public decimal FirstBAID { get; set; }
public decimal SecondBAID { get; set; }
public decimal ThirdBAID { get; set; }
}
public class SponsorInfoList
{
public Dictionary<string, SponsorInfo> SIList { set; get; }
}
Deserialize the file as,
var obj = JsonConvert.DeserializeObject<SIList >(File.ReadAllText(FileName));
Then you can read it,
foreach(var listItem in res.SIList )
{
Console.WriteLine("SponsorID ={0}, FirstBAID ={1}, SecondBAID ={2}, ThirdBAID ={3}", listItem.SponsorID, listItem.FirstBAID, listItem.SecondBAID, listItem.ThirdBAID );
}
There may be syntactical errors but the approach remains same.
Feel free to leave a message!
You need to deserialize into your object like:
Sponsor spon = JsonConvert.DeserializeObject<Sponsor>(json);
So I have the json below that I want to Deseralize into Classes so I can work with it. But the issues is that the top two fields are a different type to all the rest
"items": {
"averageItemLevel": 718,
"averageItemLevelEquipped": 716,
"head": { ... },
"chest": { ... },
"feet": { ... },
"hands": { ... }
}
Where ... is a the Item class below, but the problem is that 2 of the fields are ints and the rest are Item, there are about 20 fields in total. So what I'd like to do is put them into a Dictionary<string, Item> but the 2 int fields are preventing me from Deseralizing it into that. I'm using JavaScriptSerializer.Deserialize<T>() to do this.
I could have each item as it's own class with the name of the item as the name of the class, but I find that to be very bad, repeating so much each time, also very hard to work with later since I cant iterate over the fields, where as I could a Dictionary. Any idea how I could overcome this?
public class Item
{
public ItemDetails itemDetails { get; set; }
public int id { get; set; }
public string name { get; set; }
public string icon { get; set; }
public int quality { get; set; }
public int itemLevel { get; set; }
public TooltipParams tooltipParams { get; set; }
public List<Stat> stats { get; set; }
public int armor { get; set; }
public string context { get; set; }
public List<int> bonusLists { get; set; }
}
Update: from the comments I came up with this solution
JObject jsonObject = JObject.Parse(json);
jsonObject["averageItemLevel"] = int.Parse(jsonObject["items"]["averageItemLevel"].ToString());
jsonObject["averageItemLevelEquipped"] = int.Parse(jsonObject["items"]["averageItemLevelEquipped"].ToString());
jsonObject["items"]["averageItemLevel"].Parent.Remove();
jsonObject["items"]["averageItemLevelEquipped"].Parent.Remove();
var finalJson = jsonObject.ToString(Newtonsoft.Json.Formatting.None);
var character = _serializer.Deserialize<Character>(finalJson);
character.progression.raids.RemoveAll(x => x.name != "My House");
return character
If I add these two classes to match your JSON I can serialize and deserialize the objects:
public class root
{
public Items items { get; set; }
}
public class Items
{
public int averageItemLevel { get; set; }
public int averageItemLevelEquipped { get; set; }
public Item head {get;set;}
public Item chest {get;set;}
public Item feet {get;set;}
public Item hands {get;set;}
}
Test rig with the WCF Serializer:
var obj = new root();
obj.items = new Items
{
averageItemLevel = 42,
feet = new Item { armor = 4242 },
chest = new Item { name = "super chest" }
};
var ser = new DataContractJsonSerializer(typeof(root));
using (var ms = new MemoryStream())
{
ser.WriteObject(ms, obj);
Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));
Console.WriteLine("and deserialize");
ms.Position = 0;
var deserializeObject = (root) ser.ReadObject(ms);
Console.WriteLine(deserializeObject.items.feet.armor);
}
And with the JavaScriptSerializer:
var jsser = new JavaScriptSerializer();
var json = jsser.Serialize(obj);
Console.WriteLine(json);
Console.WriteLine("and deserialize");
var djson = jsser.Deserialize<root>(json);
Console.WriteLine(djson.items.feet.armor);
Both serializers give the same result for your given JSON.
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