Related
How to Deserialize XML document
My XML
<Title>
<NAME>ABC</NAME>
<BODY>
<A>IAG4</A>
<B>
<B1>
<C>100</C>
<C>EC0001</C1>
<C2>DEF</C2>
<C3>100</C3>
<C4>200</C4>
<C5>600</C5>
<C6>1000</C6>
</B1>
<B1>
<D>101</D>
<D1>EC0002</D1>
</B1>
</B>
</BODY>
</Title>
I want to deserialize this into a class and I want to access them with the objects of the class created. I am using C#.
Use xml serialization code as shown below
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XmlReader reader = XmlReader.Create(FILENAME);
XmlSerializer serializer = new XmlSerializer(typeof(Message));
Message message = (Message)serializer.Deserialize(reader);
}
}
[XmlRoot("MESSAGE")]
public class Message
{
[XmlElement("NAME")]
public string name { get; set; }
[XmlElement("BODY")]
public Body body { get; set; }
}
public class Body
{
[XmlElement("EQPID")]
public string eqpid { get; set; }
[XmlArray("ECS")]
[XmlArrayItem("EC")]
public List<EC> ec { get; set; }
}
public class EC
{
public int ECID { get; set; }
public string ECNAME { get; set; }
public string ECDEF { get; set; }
public int ECSLL { get; set; }
public int ECSUL { get; set; }
public int ECWLL { get; set; }
public int ECWUL { get; set; }
}
}
You could use online tools like Xml2Csharp to generate classes needed to store your XML Data. To deserialize the Xml, you could then use the XmlSerializer
XmlSerializer serializer = new XmlSerializer(typeof(MESSAGE));
using (TextReader reader = new StringReader(xml))
{
var result = (MESSAGE)serializer.Deserialize(reader);
}
Where your classes are defined as
[XmlRoot(ElementName="EC")]
public class EC
{
[XmlElement(ElementName="ECID")]
public string ECID { get; set; }
[XmlElement(ElementName="ECNAME")]
public string ECNAME { get; set; }
[XmlElement(ElementName="ECDEF")]
public string ECDEF { get; set; }
[XmlElement(ElementName="ECSLL")]
public string ECSLL { get; set; }
[XmlElement(ElementName="ECSUL")]
public string ECSUL { get; set; }
[XmlElement(ElementName="ECWLL")]
public string ECWLL { get; set; }
[XmlElement(ElementName="ECWUL")]
public string ECWUL { get; set; }
}
[XmlRoot(ElementName="ECS")]
public class ECS
{
[XmlElement(ElementName="EC")]
public List<EC> EC { get; set; }
}
[XmlRoot(ElementName="BODY")]
public class BODY
{
[XmlElement(ElementName="EQPID")]
public string EQPID { get; set; }
[XmlElement(ElementName="ECS")]
public ECS ECS { get; set; }
}
[XmlRoot(ElementName="MESSAGE")]
public class MESSAGE
{
[XmlElement(ElementName="NAME")]
public string NAME { get; set; }
[XmlElement(ElementName="BODY")]
public BODY BODY { get; set; }
}
I am successfully able to retrieve the JSON body from a URL in Visual Studio 2019 using Newtonsoft library. However I'm having difficulty in parsing out the only variable I am interested in.
I've tried to follow some guides on here that I don't seem to have either implemented correctly or haven't fully understood (I'm pretty new to this).
e.g.
Unexpected character encountered while parsing API response
RAW JSON:
{"deviceId":37,"longMacAddress":"5884e40000000439","shortMacAddress":259,"hoplist":"(259,3)","associationTime":"2019-06-10 22:43:54","lifeCheckInterval":5,"lastLiveCheck":"2019-06-11 07:11:37","onlineStatus":1,"txPowerValue":14,"deviceType":1,"frequencyBand":1,"lastLivecheck":"2019-06-11 07:11:36","disassociationState":0,"firmwareUpdateActivated":0,"firmwareUpdatePackagesSent":0,"firmwareUpdatePackagesUnsent":0,"firmwareUpdateInProgress":0,"deviceIdOem":"-1","deviceNameOem":"-1","deviceCompanyOem":"-1","binaryInputCount":0,"binaryOutputCount":0,"analogInputCount":0,"characterStringCount":1,"location":[{"location":"UK","locationWriteable":1,"changedAt":"2019-06-10 23:40:50"}],"description":[{"description":"DevKit","descriptionWriteable":1,"changedAt":"2019-06-10 23:40:54"}],"binaryInput":[],"binaryOutput":[],"analogInput":[],"characterString":[{"characterString":"149+0.0+99+26.5+0","characterStringWriteable":1,"changedAt":"2019-06-11 06:45:02"}]}
MY MAIN CODE:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace API_JSON_1
{
class Program
{
static void Main(string[] args)
{
var client = new WebClient();
var JSON = client.DownloadString("http://192.168.0.254:8000/nodes/longmac/5884e40000000439");
Console.WriteLine(JSON);
Console.WriteLine("----------------------------------------------");
CharacterString CSV = JsonConvert.DeserializeObject<CharacterString>(JSON);
Console.WriteLine("Sensor data: " + CSV.CharacterStringCharacterString);
}
}
}
MY CHARACTER STRING CLASS:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace API_JSON_1
{
public class CharacterStrings
{
public CharacterStrings CharString { get; set; }
}
public class CharacterString
{ public string CharacterStringCharacterString { get; set; }
public long CharacterStringWriteable { get; set; }
public DateTimeOffset ChangedAt { get; set; }
}
}
OUTPUT TO THE CONSOLE:
{"deviceId":37,"longMacAddress":"5884e40000000439","shortMacAddress":259,"hoplis
t":"(259,3)","associationTime":"2019-06-10 22:43:54","lifeCheckInterval":5,"last
LiveCheck":"2019-06-11 06:56:37","onlineStatus":1,"txPowerValue":14,"deviceType"
:1,"frequencyBand":1,"lastLivecheck":"2019-06-11 06:56:33","disassociationState"
:0,"firmwareUpdateActivated":0,"firmwareUpdatePackagesSent":0,"firmwareUpdatePac
kagesUnsent":0,"firmwareUpdateInProgress":0,"deviceIdOem":"-1","deviceNameOem":"
-1","deviceCompanyOem":"-1","binaryInputCount":0,"binaryOutputCount":0,"analogIn
putCount":0,"characterStringCount":1,"location":[{"location":"UK","locati
onWriteable":1,"changedAt":"2019-06-10 23:40:50"}],"description":[{"description"
:"DevKit","descriptionWriteable":1,"changedAt":"2019-06-10 23:40:54"}],"binaryIn
put":[],"binaryOutput":[],"analogInput":[],"characterString":[{"characterString"
:"149+0.0+99+26.5+0","characterStringWriteable":1,"changedAt":"2019-06-11 06:45:
02"}]}
----------------------------------------------
Sensor data:
Press any key to continue . . .
Obviously I was expecting/hoping that the penultimate line there would read:
"Sensor data: 149+0.0+99+26.5+0"
In order for this to work you have to modify your classes like this:
public class CharacterStrings
{
public List<CharacterStringObject> CharacterString { get; set; }
}
public class CharacterStringObject
{
public string CharacterString { get; set; }
public long CharacterStringWriteable { get; set; }
public DateTime ChangedAt { get; set; }
}
After that, after you read your JSON like that:
CharacterString CSV = JsonConvert.DeserializeObject<CharacterString>(JSON);
You end up with List<CharacterStringObject> with one element in it. So you take the first one like that and print it:
Console.WriteLine("Sensor data: " + CSV.CharacterString.First().CharacterString);
Cheers,
Edit: Tested it locally with your given JSON, works fine
Welcome to StackOverflow!
Something you need to keep in mind when converting a json string to an object (ie: Deserialize) is that the object to which you are converting the string into needs to match the format of the json string. In your case, the json string does not match the object to which you are converting.
Once you have the correct object, this will give you the output you want:
static void Main(string[] args)
{
string JSON = "{\"deviceId\":37,\"longMacAddress\":\"5884e40000000439\",\"shortMacAddress\":259,\"hoplist\":\"(259,3)\",\"associationTime\":\"2019-06-10 22:43:54\",\"lifeCheckInterval\":5,\"lastLiveCheck\":\"2019-06-11 07:11:37\",\"onlineStatus\":1,\"txPowerValue\":14,\"deviceType\":1,\"frequencyBand\":1,\"lastLivecheck\":\"2019-06-11 07:11:36\",\"disassociationState\":0,\"firmwareUpdateActivated\":0,\"firmwareUpdatePackagesSent\":0,\"firmwareUpdatePackagesUnsent\":0,\"firmwareUpdateInProgress\":0,\"deviceIdOem\":\"-1\",\"deviceNameOem\":\"-1\",\"deviceCompanyOem\":\"-1\",\"binaryInputCount\":0,\"binaryOutputCount\":0,\"analogInputCount\":0,\"characterStringCount\":1,\"location\":[{\"location\":\"UK\",\"locationWriteable\":1,\"changedAt\":\"2019-06-10 23:40:50\"}],\"description\":[{\"description\":\"DevKit\",\"descriptionWriteable\":1,\"changedAt\":\"2019-06-10 23:40:54\"}],\"binaryInput\":[],\"binaryOutput\":[],\"analogInput\":[],\"characterString\":[{\"characterString\":\"149+0.0+99+26.5+0\",\"characterStringWriteable\":1,\"changedAt\":\"2019-06-11 06:45:02\"}]}";
Console.WriteLine(JSON);
Console.WriteLine("----------------------------------------------");
RootObject CSV = JsonConvert.DeserializeObject<RootObject>(JSON);
// Option 1: Loop over the items in your List<CharacterString>...
foreach (var cs in CSV.characterString)
{
Console.WriteLine("Sensor data: " + cs.characterString);
}
// Option 2: Or, if you know there is only one in the list...
Console.WriteLine("Sensor data: " + CSV.characterString.First().characterString);
}
EDIT to explain the code above: Because characterString is a List<CharacterString>, it's technically possible that you could have more than one item in that list. Option 1: If you want, you can loop through that list to display the items in it. But if you know for certain that there will only be one item in the list, then, Option 2: You can just display the .First() item in the list.
I took the json sting you gave us, and using this handy website (http://json2csharp.com/#) I converted it into the following classes:
public class RootObject
{
public int deviceId { get; set; }
public string longMacAddress { get; set; }
public int shortMacAddress { get; set; }
public string hoplist { get; set; }
public string associationTime { get; set; }
public int lifeCheckInterval { get; set; }
public string lastLiveCheck { get; set; }
public int onlineStatus { get; set; }
public int txPowerValue { get; set; }
public int deviceType { get; set; }
public int frequencyBand { get; set; }
public string lastLivecheck { get; set; }
public int disassociationState { get; set; }
public int firmwareUpdateActivated { get; set; }
public int firmwareUpdatePackagesSent { get; set; }
public int firmwareUpdatePackagesUnsent { get; set; }
public int firmwareUpdateInProgress { get; set; }
public string deviceIdOem { get; set; }
public string deviceNameOem { get; set; }
public string deviceCompanyOem { get; set; }
public int binaryInputCount { get; set; }
public int binaryOutputCount { get; set; }
public int analogInputCount { get; set; }
public int characterStringCount { get; set; }
public List<Location> location { get; set; }
public List<Description> description { get; set; }
public List<object> binaryInput { get; set; }
public List<object> binaryOutput { get; set; }
public List<object> analogInput { get; set; }
public List<CharacterString> characterString { get; set; }
}
public class Location
{
public string location { get; set; }
public int locationWriteable { get; set; }
public string changedAt { get; set; }
}
public class Description
{
public string description { get; set; }
public int descriptionWriteable { get; set; }
public string changedAt { get; set; }
}
public class CharacterString
{
public string characterString { get; set; }
public int characterStringWriteable { get; set; }
public string changedAt { get; set; }
}
The CharacterString property in the json is an array of objects. Also the first property in those objects is characterString. Below is a working example
Output is Sensor Data: 149+0.0+99+26.5+0
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
namespace SOTest
{
class Program
{
static void Main(string[] args)
{
var json =
"{\"deviceId\":37,\"longMacAddress\":\"5884e40000000439\",\"shortMacAddress\":259,\"hoplist\":\"(259,3)\",\"associationTime\":\"2019-06-10 22:43:54\",\"lifeCheckInterval\":5,\"lastLiveCheck\":\"2019-06-11 07:11:37\",\"onlineStatus\":1,\"txPowerValue\":14,\"deviceType\":1,\"frequencyBand\":1,\"lastLivecheck\":\"2019-06-11 07:11:36\",\"disassociationState\":0,\"firmwareUpdateActivated\":0,\"firmwareUpdatePackagesSent\":0,\"firmwareUpdatePackagesUnsent\":0,\"firmwareUpdateInProgress\":0,\"deviceIdOem\":\"-1\",\"deviceNameOem\":\"-1\",\"deviceCompanyOem\":\"-1\",\"binaryInputCount\":0,\"binaryOutputCount\":0,\"analogInputCount\":0,\"characterStringCount\":1,\"location\":[{\"location\":\"UK\",\"locationWriteable\":1,\"changedAt\":\"2019-06-10 23:40:50\"}],\"description\":[{\"description\":\"DevKit\",\"descriptionWriteable\":1,\"changedAt\":\"2019-06-10 23:40:54\"}],\"binaryInput\":[],\"binaryOutput\":[],\"analogInput\":[],\"characterString\":[{\"characterString\":\"149+0.0+99+26.5+0\",\"characterStringWriteable\":1,\"changedAt\":\"2019-06-11 06:45:02\"}]}";
var obj = JsonConvert.DeserializeObject<CharacterStrings>(json);
Console.WriteLine($"Sensor Data: {obj.CharacterString.First().CharacterString}");
Console.ReadKey();
}
public class CharacterStrings
{
public List<Characters> CharacterString { get; set; }
}
public class Characters
{ public string CharacterString { get; set; }
public long CharacterStringWriteable { get; set; }
public DateTime ChangedAt { get; set; }
}
}
}
You are defining the CSV object with CharacterSting. I should be CharacterStrings and Inside the CharacterStrings class it should to be array because your JSON is an array
I am trying to make simple UWP weather app, just for learning purpose, and I am having trouble getting data from JSON.
How to get min and max temperature from public class ConsolidatedWeather?
I can get data from other classes.
Thanks a lot
Vrime.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace _01_Weaather
{
class Vrime
{
public async static Task<ConsolidatedWeather> ShowTemp()
{
var http = new HttpClient();
var url = String.Format("https://www.metaweather.com/api/location/44418/");
var response = await http.GetAsync(url);
var result = await response.Content.ReadAsStringAsync();
var ser = new DataContractJsonSerializer(typeof(ConsolidatedWeather));
var ms = new MemoryStream(Encoding.UTF8.GetBytes(result));
var data = (ConsolidatedWeather)ser.ReadObject(ms);
return data;
}
}
[DataContract]
public class ConsolidatedWeather
{
[DataMember]
public object id { get; set; }
[DataMember]
public string weather_state_name { get; set; }
[DataMember]
public string weather_state_abbr { get; set; }
[DataMember]
public string wind_direction_compass { get; set; }
[DataMember]
public string created { get; set; }
[DataMember]
public string applicable_date { get; set; }
[DataMember]
public double min_temp { get; set; }
[DataMember]
public double max_temp { get; set; }
[DataMember]
public double the_temp { get; set; }
[DataMember]
public double wind_speed { get; set; }
[DataMember]
public double wind_direction { get; set; }
[DataMember]
public double air_pressure { get; set; }
[DataMember]
public int humidity { get; set; }
[DataMember]
public double? visibility { get; set; }
[DataMember]
public int predictability { get; set; }
}
[DataContract]
public class Parent
{
[DataMember]
public string title { get; set; }
[DataMember]
public string location_type { get; set; }
[DataMember]
public int woeid { get; set; }
[DataMember]
public string latt_long { get; set; }
}
[DataContract]
public class Source
{
[DataMember]
public string title { get; set; }
[DataMember]
public string slug { get; set; }
[DataMember]
public string url { get; set; }
[DataMember]
public int crawl_rate { get; set; }
}
[DataContract]
public class RootObject
{[DataMember]
public List<ConsolidatedWeather> consolidated_weather { get; set; }
[DataMember]
public string time { get; set; }
[DataMember]
public string sun_rise { get; set; }
[DataMember]
public string sun_set { get; set; }
[DataMember]
public string timezone_name { get; set; }
[DataMember]
public Parent parent { get; set; }
[DataMember]
public List<Source> sources { get; set; }
[DataMember]
public string title { get; set; }
[DataMember]
public string location_type { get; set; }
[DataMember]
public int woeid { get; set; }
[DataMember]
public string latt_long { get; set; }
[DataMember]
public string timezone { get; set; }
}
MainPage.xaml
namespace _01_Weaather
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
double min;
double max;
public MainPage()
{
this.InitializeComponent();
}
private async void BtnPrikaz_OnClick(object sender, RoutedEventArgs e)
{
ConsolidatedWeather cWeather = await Vrime.ShowTemp();
min =cWeather.min_temp;
max = cWeather.max_temp;
txtTemp.Text = String.Format(min.ToString() + "\n"+ max.ToString());
}
}
Your deserializing is not on the correct object. It should be on RootObject. As the JSON retured by weather API returns data for future dates as well so if you need Min and Max temperature for today then below is the sample code.
public async Task<RootObject> ShowTemp()
{
var http = new HttpClient();
var url = String.Format("https://www.metaweather.com/api/location/44418/");
var response = await http.GetAsync(url);
var result = await response.Content.ReadAsStringAsync();
var ser = new DataContractJsonSerializer(typeof(RootObject));
var ms = new MemoryStream(Encoding.UTF8.GetBytes(result));
var data = (RootObject)ser.ReadObject(ms);
return data;
}
public async Task<ConsolidatedWeather> GetWeatherForToday()
{
RootObject ro = await ShowTemp();
ConsolidatedWeather todayWeather = ro.consolidated_weather.FirstOrDefault();
return todayWeather;
// for getting min and max
// todayWeather.min_temp;
// todayWeather.max_temp;
}
try changing the data types of the attributes min & max temperature to float and you are using wrong object type to deserialize. use your root object. Also, i'd recommend using something like restsharp for api consumption. thats going to make your life 2X easier.
I would like to read in a json respons to my c# class for learning and having problem with it.
This is the main code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using Newtonsoft.Json;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
var webClient = new System.Net.WebClient();
var json = webClient.DownloadString("https://api.trafiklab.se/samtrafiken/resrobotstops/GetDepartures.json?key=[KEY]&apiVersion=2.2&locationId=7420752&coordSys=RT90");
This url will return this json
{"getdeparturesresult":{"departuresegment":[{"departure":{"location":
{"#id":"7420752","#x":"1271307","#y":"6404493","name":"Göteborg Brunnsparken"}
,"datetime":"2014-12-10 12:27"},"direction":"Göteborg Kålltorp","segmentid":
{"mot":{"#displaytype":"S","#type":"SLT","#text":"Spårvagn"},"carrier":
{"name":"Västtrafik","url":"http:\/\/www.vasttrafik.se\/","id":"279","number":"3"}}},
The first problem is that when generating a c# class it will complain about the # in the variable name. How can this be fixed? I mean I cant change the json respons. That is what I get. My guess would be this:
getdeparturesresult.departuresegment.departure.location["#x"]);
The second is how will I write to get it in to my class? What should be used?
I have tried this but then it will complain about my RootObject:
string json = r.ReadToEnd();
List<RootObject> items = JsonConvert.DeserializeObject<List<RootObject>>(json);
Lets say I got a class like this
public class Location
{
public string id { get; set; }
public string x { get; set; }
public string y { get; set; }
public string name { get; set; }
}
public class Departure
{
public Location location { get; set; }
public string datetime { get; set; }
}
public class Mot
{
public string displaytype { get; set; }
public string type { get; set; }
public string text { get; set; }
}
public class Carrier
{
public string name { get; set; }
public string url { get; set; }
public string id { get; set; }
public string number { get; set; }
}
public class Segmentid
{
public Mot mot { get; set; }
public Carrier carrier { get; set; }
}
public class Departuresegment
{
public Departure departure { get; set; }
public string direction { get; set; }
public Segmentid segmentid { get; set; }
}
public class Getdeparturesresult
{
public Departuresegment departuresegment { get; set; }
}
public class RootObject
{
public Getdeparturesresult getdeparturesresult { get; set; }
}
I have also tried this
dynamic array = JsonConvert.DeserializeObject(json);
foreach (var item in array)
{
Console.WriteLine("{0}", item);
}
This will printout whats in the json. But how do I get it to be read into my class? I cant figure it out. It must be simple but I cant get it right.
You only need to change like:
public class Getdeparturesresult
{
public IEnumerable<Departuresegment> departuresegment { get; set; }
}
You can still use the Json.net serializer (JsonConvert).
Edit:
To handle the "#id" property you can do this:
[JsonProperty("#id")]
public string id { get; set; }
You could accomplish that with JavaScriptSerializer.
var root = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<RootObject>(json);
It worked for me, but I had to change the type of Getdeparturesresult.departuresegment property to an array:
public class Getdeparturesresult
{
public Departuresegment[] departuresegment { get; set; }
}
Update:
To deserialize JSON properties with special characters with .NET, you can use DataContractJsonSerializer.
RootObject root;
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
root = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(RootObject)).ReadObject(stream) as RootObject;
But your code will have to get verbose. You need to mark every class with [DataContract] and every property with [DataMember] attributes. For the properties whose names are not equal to those of the source, use [DataMember(Name = "#fancy_name")].
[DataContract]
public class Location
{
[DataMember(Name = "#id")]
public string id { get; set; }
[DataMember(Name = "#x")]
public string x { get; set; }
[DataMember(Name = "#y")]
public string y { get; set; }
[DataMember]
public string name { get; set; }
}
// etc.
Environment:
I have data stored in SQL2000 database and I am using VWD to maintain our company website.
In the past I use asp.net + SQL database as the interface for various department until I met Json.NET.
Business Process:
Here is what I want to realize. I have several tables in our SQL database, from which I can query the project tasks, assignments... based on the users' selection or input in my aspx webpage. I would like to serialize the dataset into JSON for further processing (in a word, it could be visualized in the form as gantt chart in the webpage).
Here below is the JSON example:
{"tasks":[
{"id":-1,"name":"Gantt editor","code":"","level":0,"status":"STATUS_ACTIVE","start":1346623200000,"duration":16,"end":1348523999999,"startIsMilestone":true,"endIsMilestone":false,"assigs":[]},
{"id":-2,"name":"coding","code":"","level":1,"status":"STATUS_ACTIVE","start":1346623200000,"duration":10,"end":1347659999999,"startIsMilestone":false,"endIsMilestone":false,"assigs":[],"description":"","progress":0},
],
"selectedRow":0,
"deletedTaskIds":[],
"canWrite":true,
"canWriteOnParent":true }
In order to do so, I first construct the class based on the JSON format above. Here below is what I wrote:
public class ganttData
{
public class Tasks
{
public int id { get; set; }
public string name { get; set; }
public string code { get; set; }
public int level { get; set; }
public string status { get; set; }
public object start { get; set; }
public int duration { get; set; }
public object end { get; set; }
public bool startIsMilestone { get; set; }
public bool endIsMilestone { get; set; }
public List<object> assigs { get; set; }
public string description { get; set; }
public int? progress { get; set; }
public string depends { get; set; }
}
public int selectedRow { get; set; }
public List<object> deletedTaskIds { get; set; }
public bool canWrite { get; set; }
public bool canWriteOnParent { get; set; }
}
The reason why I want to construct the class is that I would like to have a test first and see if the program could work or not.
But it seems it doesn't work out.
For sure you master have better ways to do so but this is the best way that I could come out with after many times of failure attemps.
Current Status:
So far I could successfully retrieve the SQL Table Data as dataset but I don't know how to serialize the retrieved data into JSON.
Millions of thanks for your help.
Schumann
Here below is the code in my ***.aspx.cs file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using System.IO;
using System.Configuration;
public partial class Test_JNetToFile : System.Web.UI.Page
{
public class ganttData
{
public class Tasks
{
public int id { get; set; }
public string name { get; set; }
public string code { get; set; }
public int level { get; set; }
public string status { get; set; }
public object start { get; set; }
public int duration { get; set; }
public object end { get; set; }
public bool startIsMilestone { get; set; }
public bool endIsMilestone { get; set; }
public List<object> assigs { get; set; }
public string description { get; set; }
public int? progress { get; set; }
public string depends { get; set; }
}
//public List<Task> tasks { get; set; }
public int selectedRow { get; set; }
public List<object> deletedTaskIds { get; set; }
public bool canWrite { get; set; }
public bool canWriteOnParent { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
////get the connection string from web.config
////uncomment the following if you need to access sql database
////---------------------------------- Database connection----------------------------------------------
//string connString = ConfigurationManager.ConnectionStrings["ShipmentConnectionString"].ConnectionString;
//DataSet dataSet = new DataSet();
//using (SqlConnection conn = new SqlConnection(connString))
//{
// SqlDataAdapter adapter = new SqlDataAdapter();
// adapter.SelectCommand = new SqlCommand("select * from Gantt where Nr < 5", conn);
// conn.Open();
// adapter.Fill(dataSet);
//}
//string json = JsonConvert.SerializeObject(dataSet, Formatting.Indented);
////---------------------------------- Database connection----------------------------------------------
ganttData gd = new ganttData
{
Tasks =
{
{id = -1,name = "Gantt editor","code":"","level":0,"status":"STATUS_ACTIVE","start":1346623200000,"duration":16,"end":1348523999999,"startIsMilestone":true,"endIsMilestone":false,"assigs":[]},
{id = -2,name = "coding","code":"","level":1,"status":"STATUS_ACTIVE","start":1346623200000,"duration":10,"end":1347659999999,"startIsMilestone":false,"endIsMilestone":false,"assigs":[],"description":"","progress":0},
{id = -3,name = "gant part","code":"","level":2,"status":"STATUS_ACTIVE","start":1346623200000,"duration":2,"end":1346795999999,"startIsMilestone":false,"endIsMilestone":false,"assigs":[],"depends":""},
{id = -4,name = "editor part","code":"","level":2,"status":"STATUS_SUSPENDED","start":1346796000000,"duration":4,"end":1347314399999,"startIsMilestone":false,"endIsMilestone":false,"assigs":[],"depends":"3"},
{id = -5,name = "testing","code":"","level":1,"status":"STATUS_SUSPENDED","start":1347832800000,"duration":6,"end":1348523999999,"startIsMilestone":false,"endIsMilestone":false,"assigs":[],"depends":"2:5","description":"","progress":0},
{id = -6,name = "test on safari","code":"","level":2,"status":"STATUS_SUSPENDED","start":1347832800000,"duration":2,"end":1348005599999,"startIsMilestone":false,"endIsMilestone":false,"assigs":[],"depends":""},
{id = -7,name = "test on ie","code":"","level":2,"status":"STATUS_SUSPENDED","start":1348005600000,"duration":3,"end":1348264799999,"startIsMilestone":false,"endIsMilestone":false,"assigs":[],"depends":"6"},
{id = -8,name = "test on chrome","code":"","level":2,"status":"STATUS_SUSPENDED","start":1348005600000,"duration":2,"end":1348178399999,"startIsMilestone":false,"endIsMilestone":false,"assigs":[],"depends":"6"}
},
selectedRow = 0,
deletedTaskIds = [],
canWrite = true,
canWriteOnParent = true
};
// serialize JSON to a string and then write string to a file
File.WriteAllText(#"c:\movie.json", JsonConvert.SerializeObject(movie));
// serialize JSON directly to a file
using (StreamWriter file = File.CreateText(#"c:\movie.json"))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, movie);
}
//Label1.Text = json;
}
}