RestSharp: ItemChoice always null - c#

I'm new to RestSharp and trying to access my subsonic server through the subsonic-api.
Every Response in wrapped in a subsonic-response Tag, e.g.
<subsonic-response xmlns="http://subsonic.org/restapi"
status="ok" version="1.10.1">
<artists ignoredArticles="The El La Los Las Le Les">
<index name="A">
<artist id="5449" name="A-Ha" coverArt="ar-5449" albumCount="4"/>
<artist id="5421" name="ABBA" coverArt="ar-5421" albumCount="6"/>
<artist id="5432" name="AC/DC" coverArt="ar-5432" albumCount="15"/>
<artist id="6633" name="Aaron Neville" coverArt="ar-6633" albumCount="1"/>
</index>
<index name="B">
<artist id="5950" name="Bob Marley" coverArt="ar-5950" albumCount="8"/>
<artist id="5957" name="Bruce Dickinson" coverArt="ar-5957" albumCount="2"/>
</index>
</artists>
Xsd generated the following classes for serialization:
public partial class Response
{
private object itemField;
private ItemChoiceType itemElementNameField;
private ResponseStatus statusField;
private string versionField;
[System.Xml.Serialization.XmlChoiceIdentifierAttribute("ItemElementName")]
public object Item
{
get
{
return this.itemField;
}
set
{
this.itemField = value;
}
}
[System.Xml.Serialization.XmlIgnoreAttribute()]
public ItemChoiceType ItemElementName
{
get
{
return this.itemElementNameField;
}
set
{
this.itemElementNameField = value;
}
}
public ResponseStatus status
{
get
{
return this.statusField;
}
set
{
this.statusField = value;
}
}
public string version
{
get
{
return this.versionField;
}
set
{
this.versionField = value;
}
}
}
public partial class ArtistsID3
{
private List<IndexID3> indexField;
public ArtistsID3()
{
this.indexField = new List<IndexID3>();
}
public List<IndexID3> index
{
get
{
return this.indexField;
}
set
{
this.indexField = value;
}
}
}
public enum ItemChoiceType
{
/// <remarks/>
album,
/// <remarks/>
albumList,
--- snip ----
When I'm trying to deserialize into a Response-Object the field Item is always null and ItemElementName gets the first value from the enum ItemChoiceType but version and status are correctly set. The retrieved xml-output looks like expected (see sample).
What works though is deserializing into ArtistsID3 but then I loose the status.
Here's the code:
SubsonicApi api = new SubsonicApi();
var request = new RestRequest();
request.Resource = "getArtists.view";
request.AddParameter("v", "1.10.2");
request.AddParameter("c", "no name yet");
// Item always null!
// var response = api.Execute<Response>(request);
var response = api.Execute<ArtistsID3>(request);
public T Execute<T>(RestRequest request)
where T : new()
{
var client = new RestClient();
client.BaseUrl = new System.Uri(BaseUrl);
client.Authenticator = new HttpBasicAuthenticator(_accountSid, _secretKey);
var response = client.Execute<T>(request);
Console.WriteLine("RESPONSE-DATA: " + response.Content);
return response.Data;
}
I'd be glad if somebody could point me in the right direction as I think the right way should be accessing the data through an Response object. Really don't know how to debug this not expected behaviour.

try this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
SubsonicResponse subsonicResponse = new SubsonicResponse()
{
status = "ok",
version = "1.10.1",
artists = new Artists()
{
ignoredArticles = "The El La Los Las Le Les",
indexes = new List<Index>() {
new Index() {
name = "A", artists = new List<Artist>() {
new Artist() { id = 5449, name = "A-Ha", converArt = "ar-5449", albumCount = 4},
new Artist() { id = 5221, name = "ABBA", converArt = "ar-5421", albumCount = 6},
new Artist() { id = 5432, name = "AC/DC", converArt = "ar-5432", albumCount = 15},
new Artist() { id = 6633, name = "Aaron Neville", converArt = "ar-5633", albumCount = 1}
}
},
new Index() {
name = "B", artists = new List<Artist>() {
new Artist() { id = 5950, name = "Bob Marley", converArt = "ar-5950", albumCount = 8},
new Artist() { id = 5957, name = "Bruce Dickinson", converArt = "ar-5957", albumCount = 2}
}
}
}
}
};
XmlSerializer serializer = new XmlSerializer(typeof(SubsonicResponse));
StreamWriter writer = new StreamWriter(FILENAME);
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "http://subsonic.org/restapi");
serializer.Serialize(writer, subsonicResponse, ns);
writer.Flush();
writer.Close();
writer.Dispose();
XmlSerializer xs = new XmlSerializer(typeof(SubsonicResponse));
XmlTextReader reader = new XmlTextReader(FILENAME);
SubsonicResponse newSResponse = (SubsonicResponse)xs.Deserialize(reader);
}
}
[XmlRoot("subsonic-response", Namespace = "http://subsonic.org/restapi")]
public class SubsonicResponse
{
[XmlAttribute("status")]
public string status { get; set; }
[XmlAttribute("version")]
public string version { get; set; }
[XmlElement("artists")]
public Artists artists { get; set; }
}
[XmlRoot(ElementName = "artists")]
public class Artists
{
[XmlAttribute("ignoredArticles")]
public string ignoredArticles { get; set; }
[XmlElement("index")]
public List<Index> indexes { get; set; }
}
[XmlRoot("index")]
public class Index
{
[XmlAttribute("name")]
public string name { get; set; }
[XmlElement("artist")]
public List<Artist> artists { get; set; }
}
[XmlRoot("artist")]
public class Artist
{
[XmlAttribute("id")]
public int id { get; set; }
[XmlAttribute("name")]
public string name { get; set; }
[XmlAttribute("converArt")]
public string converArt { get; set; }
[XmlAttribute("albumCount")]
public int albumCount { get; set; }
}
}
​

Related

XML response format is not as my expectation

I am trying to send response as per below to the user. I am facing issue for node ITEM in which ( Type, For, Amount, Description & Rate ) present in the node as per below. But when i am trying to generate the output it is not generation output as per below for this node.
EXPECTED OUTPUT
<ANF>
<QUOTEID>951C3532</QUOTEID>
<CHARGE>161.98</CHARGE>
<ITEMIZEDCHARGES>
<ITEM TYPE="CHARGE" FOR="FREIGHT" AMOUNT="914.41" DESCRIPTION="65 LB CL125, 1 PLT # 94 x 48 x 12 IN" />
<ITEM TYPE="DISCOUNT" FOR="SHIPPER" AMOUNT="-832.11" DESCRIPTION="SHIPPER DISCOUNT" RATE="91%" />
<ITEM TYPE="CHARGE" FOR="MCADJ" AMOUNT="137.70" DESCRIPTION="ABSOLUTE MIN CHARGE ADJUSTMENT" />
</ITEMIZEDCHARGES>
<NOTES>
</NOTES>
<NUMERRORS>0</NUMERRORS>
</ANF>
I have generated the object for this xml response as per below
namespace ResponseXML
{
[XmlRoot(ElementName="ITEM")]
public class ITEM {
[XmlAttribute(AttributeName="TYPE")]
public string TYPE { get; set; }
[XmlAttribute(AttributeName="FOR")]
public string FOR { get; set; }
[XmlAttribute(AttributeName="AMOUNT")]
public string AMOUNT { get; set; }
[XmlAttribute(AttributeName="DESCRIPTION")]
public string DESCRIPTION { get; set; }
[XmlAttribute(AttributeName="RATE")]
public string RATE { get; set; }
}
[XmlRoot(ElementName="ITEMIZEDCHARGES")]
public class ITEMIZEDCHARGES {
[XmlElement(ElementName="ITEM")]
public List<ITEM> ITEM { get; set; }
}
[XmlRoot(ElementName="ANF")]
public class ANF {
[XmlElement(ElementName="QUOTEID")]
public string QUOTEID { get; set; }
[XmlElement(ElementName="CHARGE")]
public string CHARGE { get; set; }
[XmlElement(ElementName="ITEMIZEDCHARGES")]
public ITEMIZEDCHARGES ITEMIZEDCHARGES { get; set; }
[XmlElement(ElementName="NOTES")]
public string NOTES { get; set; }
[XmlElement(ElementName="NUMERRORS")]
public string NUMERRORS { get; set; }
}
}
My code output ITEMIZEDCHARGES
<ITEMIZEDCHARGES>
<ITEM>
<ITEM>
<AMOUNT>45.09</AMOUNT>
<DESCRIPTION></DESCRIPTION>
<FOR i:nil="true" />
<RATE></RATE>
<TYPE></TYPE>
</ITEM>
</ITEM>
</ITEMIZEDCHARGES>
My Code for adding values is as below in object
ITEMIZEDCHARGES _fItem = new ITEMIZEDCHARGES();
List<ITEM> fitmes = new List<ITEM>();
ITEM _item = new ITEM();
_item.AMOUNT = Convert.ToString(zipDetails.Rate);
_item.RATE = "";
_item.TYPE = "";
_item.DESCRIPTION = "";
fitmes.Add(_item);
_fItem.ITEM = fitmes;
fn.ITEMIZEDCHARGES = _fItem;
Can you please advice what i am doing mistake.
Code for response from code
[System.Web.Http.HttpPost]
[System.Web.Http.Route("GetQuote")]
[ResponseType(typeof(IEnumerable<ABF>))]
public HttpResponseMessage GetOrderPriceQuotetest(HttpRequestMessage request)
{
var abf = request.Content.ReadAsStringAsync().Result;
try
{
if (abf != null)
{
XmlSerializer serializer = new XmlSerializer(typeof(OrderPriceRequest.ABF));
using (StringReader reader = new StringReader(abf))
{
OrderPriceRequest.ABF testReq = (OrderPriceRequest.ABF)serializer.Deserialize(reader);
if (testReq != null)
{
ANF fn = new ANF();
fn.CHARGE = 0;
fn.QUOTEID = "";
ITEMIZEDCHARGES _fItem = new ITEMIZEDCHARGES();
List<ITEM> fitmes = new List<ITEM>();
ITEM _item = new ITEM();
_item.AMOUNT = "10";
_item.RATE = "";
_item.TYPE = "";
_item.DESCRIPTION = "";
fitmes.Add(_item);
_fItem.ITEMS = fitmes;
fn.ITEMIZEDCHARGES = _fItem;
return Request.CreateResponse(HttpStatusCode.OK, fn);
}
else
{
ANF fn = new ANF();
return Request.CreateResponse(HttpStatusCode.OK, fn);
}
}
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest, abf);
}
}
catch (Exception ex)
{
return request.CreateResponse(HttpStatusCode.BadRequest);
}
}

How to loop API pages and compare values for changing markers on map using xamarin.forms.maps iOS C#

I want to check each page values from the API and against the values to change the color of the map marker.
This is my API: http://194.141.118.43:3001/?id=0 where id is from 0 to 16
I want:
if from ?id=0 AL = 1 the marker should be green
if from ?id=0 AL = 2 the marker should be yellow
if from ?id=0 AL = 3 the marker should be orange
if from ?id=0 AL = 4 the marker should be red
So I want to check for all 17 stations (from ?id=0 to ?id=16)
I am currently checking the property Alertlevelwebsite in this method with this API: http://194.141.118.43:3001/stations, But now I have to check all the values from this address for each pin and I have to put a color for the largest value for each pin.
http://194.141.118.43:3001/?id=0 (from 0 to 16)
I use this example from xamarin.forms.maps - https://learn.microsoft.com/en-us/samples/xamarin/xamarin-forms-samples/workingwithmaps/ and in CustomMapRenderer class I try to change the colors in this method:
protected override MKAnnotationView GetViewForAnnotation(MKMapView mapView, IMKAnnotation annotation)
{
MKAnnotationView annotationView = null;
if (annotation is MKUserLocation)
return null;
var customPin = GetCustomPin(annotation as MKPointAnnotation);
//Get Value
c_annotation = annotation;
if (customPin == null)
{
throw new Exception("Custom pin not found");
}
annotationView = mapView.DequeueReusableAnnotation(customPin.Name);
if (annotationView == null)
{
annotationView = new CustomMKAnnotationView(annotation, customPin.Name);
annotationView.CalloutOffset = new CGPoint(0, 0);
((CustomMKAnnotationView)annotationView).Name = customPin.Name;
((CustomMKAnnotationView)annotationView).Url = customPin.Url;
((CustomMKAnnotationView)annotationView).Address = customPin.Address;
//Add First Line
((CustomMKAnnotationView)annotationView).AlertLevel = customPin.AlertLevel;
if (customPin.AlertLevel == 1)
{
annotationView.Image = UIImage.FromFile("green.png");
}
else if (customPin.AlertLevel == 2)
{
annotationView.Image = UIImage.FromFile("yellow.png");
}
else if (customPin.AlertLevel == 3)
{
annotationView.Image = UIImage.FromFile("orange.png");
}
else if (customPin.AlertLevel == 4)
{
annotationView.Image = UIImage.FromFile("red.png");
}
//Add Second Line
((CustomMKAnnotationView)annotationView).CodeNum = customPin.CodeNum;
((CustomMKAnnotationView)annotationView).MapCode = customPin.MapCode;
//Here I add the RequestUri for stations
string GenerateRequestUriStations(string endpoint)
{
string requestUri = endpoint;
requestUri += $"stations";
return requestUri;
}
//Here I need the loop from 0 to 16 every page and change the pin icons like above if statement
string GenerateRequestUri(string endpoint)
{
string requestUri = endpoint;
requestUri += $"?id=0";
return requestUri;
}
//This is the value who I need to compare result.WaterData.Ardaforecast but does not allow me to write result.WaterData.Ardaforecast and does not allow me to foreach here .. I don't know why ?
var reusult = _restServiceData.GetWaterDataForecast(GenerateRequestUriStations(Constants.EndPoint), GenerateRequestUri(Constants.EndPoint));
}
annotationView.CanShowCallout = true;
configureDetailView(annotationView);
return annotationView;
}
In the comments above the code I mean that when I write:
var reusult = _restServiceData.GetWaterDataForecast(GenerateRequestUriStations(Constants.EndPoint), GenerateRequestUri(Constants.EndPoint));
foreach (var item in IAsyncResult)
{
}
When I try to write result. automatic puts me IAsyncResult.. I don't know why.. ?
Can I get an example of how to loop all the pages and change colors on the markers ?
My GetDataFromAPI look like this:
public IEnumerable<AlertLevel> GetDataFromAPI(int mapCode)
{
var listAlert = new List<AlertLevel>();
var reusult = _restServiceData.GetWaterDataForecast(GenerateRequestUriStations(Constants.EndPoint), GenerateRequestUri(Constants.EndPoint, mapCode));
foreach (var item in reusult.WaterData.Ardaforecast[0].Items)
{
var currentData = new AlertLevel()
{
dateForecast = item.DateTimeForecast,
levelForecast = item.AlertLevelForecast
};
listAlert.Add(currentData);
}
return listAlert;
}
My GetWaterDataForecast look like this:
using System;
using System.Diagnostics;
using System.Net.Http;
using System.Threading.Tasks;
using MaritsaTundzhaForecast.Models;
using Newtonsoft.Json;
namespace MaritsaTundzhaForecast.Services
{
public class RestServiceData
{
HttpClient _client1;
HttpClient _client2;
public RestServiceData()
{
_client1 = new HttpClient();
_client2 = new HttpClient();
}
public WaterBindingData GetWaterDataForecast(string query, string query2)
{
WaterDataJson waterData = new WaterDataJson();
WaterStationsJson waterStations = new WaterStationsJson();
WaterBindingData result = new WaterBindingData();
try
{
var task = Task.Run(() => _client1.GetAsync(query));
task.Wait();
var response = task.Result;
var task2 = Task.Run(() => _client2.GetAsync(query2));
task2.Wait();
var response2 = task2.Result;
if (response.IsSuccessStatusCode && response2.IsSuccessStatusCode)
{
var content = response.Content.ReadAsStringAsync().Result;
var content2 = response2.Content.ReadAsStringAsync().Result;
var json = content2.Replace("\"ardaforecast\":[[", "\"ardaforecast\":[ {\"items\": [")
.Replace("}],{\"fieldCount\"", "}],\"details\":{\"fieldCount\"")
.Replace("}]}", "}}]}");
waterData = JsonConvert.DeserializeObject<WaterDataJson>(json);
waterStations = JsonConvert.DeserializeObject<WaterStationsJson>(content);
result.WaterData = waterData;
result.WaterStation = waterStations;
}
}
catch (Exception ex)
{
Debug.WriteLine("\t\tERROR {0}", ex.Message);
}
return result;
}
}
}
My WaterBindingData look like:
using System;
namespace MaritsaTundzhaForecast.Models
{
public class WaterBindingData
{
public WaterDataJson WaterData { get; set; }
public WaterStationsJson WaterStation { get; set; }
}
}
My WaterDataJson and WaterStations look like:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace MaritsaTundzhaForecast
{
public class WaterDataJson
{
public List<ForecastBody> Ardaforecast { get; set; }
}
public class ForecastBody
{
public ForecastItem[] Items { get; set; }
public ForecastDetails Details { get; set; }
}
public class ForecastItem
{
[JsonProperty("Dt")]
public DateTime DateTimeForecast { get; set; }
[JsonProperty("AL")]
public int AlertLevelForecast { get; set; }
}
public class ForecastDetails
{
public int fieldCount { get; set; }
public int affectedRows { get; set; }
public int insertId { get; set; }
public int serverStatus { get; set; }
public int warningCount { get; set; }
public int changedRows { get; set; }
public string message { get; set; }
public bool protocol41 { get; set; }
}
}
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace MaritsaTundzhaForecast.Models
{
public class WaterStationsJson
{
public List<ForecastStations> Stations { get; set; }
}
public class ForecastStations
{
[JsonProperty("Map_code")]
public int MapCode { get; set; }
[JsonProperty("NAME_IME")]
public string NameEN { get; set; }
[JsonProperty("NAME_CYR")]
public string NameBG { get; set; }
[JsonProperty("Alertlevelwebsite")]
public int AlertLevelStation { get; set; }
[JsonProperty("CODENUM")]
public int CodeNum { get; set; }
}
}

How to create xml with attribute using XmlSerializer?

I'm working on xml generation using list to direct xml of generic class, but getting wrong result of xml.
I want below output from XmlSerializer.
<root>
<rating city="A" code="A1">A++</rating>
<rating city="B" code="A2">A</rating>
<rating city="C" code="A3">AB</rating>
</root>
currently i'm getting this
<ratings reason="reason123">
<rating>R</rating>
</ratings>
<ratings reason="reason123">
<rating>R</rating></ratings>
C# Code
public class root
{
[XmlAttribute("city")]
public string city { get; set; }
[XmlAttribute("code")]
public string code { get; set; }
[XmlElement("rating")]
public string rating { get; set; }
}
string tempXML6 = XmlExtensions.Serialize(rootList)
static public void Serialize(object classobject)
{
XmlSerializer SerializedObject = new XmlSerializer(classobject.GetType());
using (MemoryStream xmlStream = new MemoryStream())
{
SerializedObject.Serialize(xmlStream, classobject);
xmlStream.Position = 0;
//Loads the XML document from the specified string.
XmlDocument resultDocument = new XmlDocument();
resultDocument.Load(xmlStream);
if (!string.IsNullOrEmpty(resultDocument.DocumentElement.InnerXml))
{
return resultDocument.DocumentElement.InnerXml;
}
else
{
return string.Empty;
}
}
}
please let me know what's needs to be change.
Your object model is wrong. It should be something like this.
[XmlRoot("root")]
public class Root
{
[XmlElement("rating")]
public Rating[] Ratings { get; set; }
}
public class Rating
{
[XmlAttribute("city")]
public string City { get; set; }
[XmlAttribute("code")]
public string Code { get; set; }
[XmlText]
public string Value { get; set; }
}
To serialize the object do this
Root root = new Root
{
Ratings = new Rating[]
{
new Rating { City = "A", Code = "A1", Value = "A++" },
new Rating { City = "B", Code = "A2", Value = "A" },
new Rating { City = "C", Code = "A3", Value = "AB" }
}
};
string serializedObject = Serialize(root);
This is the serialize method
public static string Serialize<T>(T item)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (StringWriter stringWriter = new StringWriter())
{
using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings { Indent = true, OmitXmlDeclaration = true }))
{
serializer.Serialize(xmlWriter, item, new XmlSerializerNamespaces(new[] { new XmlQualifiedName(string.Empty, string.Empty) }));
}
return stringWriter.ToString();
}
}
Xml output
<root>
<rating city="A" code="A1">A++</rating>
<rating city="B" code="A2">A</rating>
<rating city="C" code="A3">AB</rating>
</root>
Please Change your Class defination to like this:
[XmlTypeAttribute(AnonymousType = true)]
[XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class root
{
private rootRating[] ratingField;
[XmlElementAttribute("rating")]
public rootRating[] rating
{
get
{
return this.ratingField;
}
set
{
this.ratingField = value;
}
}
}
[XmlTypeAttribute(AnonymousType = true)]
public partial class rootRating
{
private string cityField;
private string codeField;
private string valueField;
[XmlAttributeAttribute()]
public string city
{
get
{
return this.cityField;
}
set
{
this.cityField = value;
}
}
[XmlAttributeAttribute()]
public string code
{
get
{
return this.codeField;
}
set
{
this.codeField = value;
}
}
[XmlTextAttribute()]
public string Value
{
get
{
return this.valueField;
}
set
{
this.valueField = value;
}
}
}
//try this
public static XElement SerializeRoot(IEnumerable<root> objRoot)
{
XElement serializedRoot = null;
using (MemoryStream memoryStream = new MemoryStream())
{
using (TextWriter StreamWriter = new StreamWriter(memoryStream))
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<root>));
xmlSerializer.Serialize(StreamWriter, objRoot);
serializedRoot = XElement.Parse(Encoding.UTF8.GetString(memoryStream.ToArray()));
}
}
return serializedRoot;
}

JSON format writing to file

I want to write my items by JSON format, but My files empty. Here is my two class:
public class DocPart
{
public string Title { get; set; }
public bool Checked { get; set; }
}
public class DocConfig
{
public List<DocPart> Parts { get; set; }
public static DocConfig LoadFromString(string jsonData)
{
var config = new DocConfig();
config.Parts = new List<DocPart>();
var part = new DocPart
{
Title = "chapter1",
"chapter2",
Checked = checkBox1.Checked,
checkbox2.Checked
};
config.Parts.Add(part);
var configString = config.SaveToString();
File.WriteAllText(#"C:\link to my file", configString);
var configString = File.ReadAllText(#"C:\link to my file");
var config = DocConfig.LoadFromString(configString);
foreach (var part in config.Parts)
{
if (part.Title == "chapter1")
chekbox1.Checked = part.Checked;
if (part.Title == "chapter2")
checkbox2.Checked = part.Checked;
var serializer = new DataContractJsonSerializer(typeof(DocConfig));
var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonData));
var config = (DocConfig)serializer.ReadObject(ms);
return config;
}
}
public string SaveToString()
{
var serializer = new DataContractJsonSerializer(typeof(DocConfig));
var ms = new MemoryStream();
serializer.WriteObject(ms, this);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
So I run my program, everything looks okey, but my file is still empty without any JSON format data. Maybe you could help me?
Thanks.
public class DocPart
{
public string Title { get; set; }
public bool Checked { get; set; }
}
public class DocConfig
{
public List<DocPart> Parts { get; set; }
public static DocConfig LoadFromString()
{
var config = new DocConfig();
config.Parts = new List<DocPart>();
var part1 = new DocPart
{
Title = "chapter1",
Checked = checkBox1.Checked
};
config.Parts.Add(part1);
var part2 = new DocPart
{
Title = "chapter2",
Checked = checkBox2.Checked
};
config.Parts.Add(part2);
var configString = config.SaveToString();
File.WriteAllText(#"d:\temp\test.json", configString);
configString = File.ReadAllText(#"d:\temp\test.json");
var ms = new MemoryStream(Encoding.UTF8.GetBytes(configString));
var serializer = new DataContractJsonSerializer(typeof(DocConfig));
config = (DocConfig)serializer.ReadObject(ms);
foreach (var part in config.Parts)
{
if (part.Title == "chapter1")
{
chekbox1.Checked = part.Checked;
Debug.WriteLine("chapter1" + part.Checked);
}
if (part.Title == "chapter2")
{
checkbox2.Checked = part.Checked;
Debug.WriteLine("chapter2" + part.Checked);
}
}
return config;
}
public string SaveToString()
{
var serializer = new DataContractJsonSerializer(typeof(DocConfig));
var ms = new MemoryStream();
serializer.WriteObject(ms, this);
return Encoding.UTF8.GetString(ms.ToArray());
}
}
Here's a really simple example I mocked up for you...
void Main()
{
const string filePath = #"C:\FilePath\json.txt";
const string testJson = #"{""glossary"": {""title"": ""example glossary"", ""GlossDiv"": {""title"": ""S"", ""GlossList"": {""GlossEntry"": {""ID"": ""SGML"", ""SortAs"": ""SGML"", ""GlossTerm"": ""Standard Generalized Markup Language"", ""Acronym"": ""SGML"", ""Abbrev"": ""ISO 8879:1986"", ""GlossDef"": {""para"": ""A meta-markup language, used to create markup languages such as DocBook."", ""GlossSeeAlso"": [""GML"", ""XML""]}, ""GlossSee"": ""markup""}}}}}";
// Now we have our Json Object...
SampleJson sample = JsonConvert.DeserializeObject<SampleJson>(testJson);
// We convert it back into a string with indentation...
string jsonString = JsonConvert.SerializeObject(sample, Newtonsoft.Json.Formatting.Indented);
// Now simply save to file...
using (StreamWriter writer = new StreamWriter(filePath))
{
writer.WriteLine(jsonString);
}
Process.Start(filePath);
}
// The following classes are what the `testJson` string is deserialized into.
public class GlossDef
{
[JsonProperty("para")]
public string Para { get; set; }
[JsonProperty("GlossSeeAlso")]
public string[] GlossSeeAlso { get; set; }
}
public class GlossEntry
{
[JsonProperty("ID")]
public string ID { get; set; }
[JsonProperty("SortAs")]
public string SortAs { get; set; }
[JsonProperty("GlossTerm")]
public string GlossTerm { get; set; }
[JsonProperty("Acronym")]
public string Acronym { get; set; }
[JsonProperty("Abbrev")]
public string Abbrev { get; set; }
[JsonProperty("GlossDef")]
public GlossDef GlossDef { get; set; }
[JsonProperty("GlossSee")]
public string GlossSee { get; set; }
}
public class GlossList
{
[JsonProperty("GlossEntry")]
public GlossEntry GlossEntry { get; set; }
}
public class GlossDiv
{
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("GlossList")]
public GlossList GlossList { get; set; }
}
public class Glossary
{
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("GlossDiv")]
public GlossDiv GlossDiv { get; set; }
}
public class SampleJson
{
[JsonProperty("glossary")]
public Glossary Glossary { get; set; }
}

How can i add list data in my object in visual studio 2005?

Below codes run perfectly but i want to re generate simply
static void YeniMethodListele()
{
Calısan calisan = new Calısan(){ ID=1, Ad="xxx", SoyAd="yyy"};
List<Calısan> myList = new List<Calısan>();
myList.Add(calisan);
MyCalısan myCalısan = new MyCalısan() { list = myList };
//myCalısan.list.Add(calisan);
foreach (Calısan item in myCalısan.list)
{
Console.WriteLine(item.Ad.ToString());
}
}
}
public class Calısan
{
public int ID { get; set; }
public string Ad { get; set; }
public string SoyAd { get; set; }
}
public class MyCalısan
{
public List<Calısan> list { get; set; }
public MyCalısan()
{
list = new List<Calısan>();
}
}
Here is a sample of a couple of ways to create the list a little more simply. Note the small change to the Calısan object to give it a default constructor and an overloaded constructor.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
////Calısan calisan = new Calısan() { ID = 1, Ad = "xxx", SoyAd = "yyy" };
MyCalısan myCalısan = new MyCalısan();
//option 1:
//==========
myCalısan.list.AddRange(new[] { new Calısan() { ID = 1, Ad = "xxx", SoyAd = "yyyy" }, new Calısan() { ID = 2, Ad = "blah", SoyAd = "jiggy" } });
//option 2:
//=========
myCalısan.list.AddRange(new[] { new Calısan(1, "xxx", "yyy"), new Calısan(2, "blah", "jiggy") });
////myCalısan.list.Add(calisan);
foreach (Calısan item in myCalısan.list)
{
Console.WriteLine(item.Ad.ToString());
}
Console.ReadKey();
}
}
public class Calısan
{
public Calısan() { }
public Calısan(int id, string ad, string soyad)
{
ID = id;
Ad = ad;
SoyAd = soyad;
}
public int ID { get; set; }
public string Ad { get; set; }
public string SoyAd { get; set; }
}
public class MyCalısan
{
public List<Calısan> list { get; set; }
public MyCalısan()
{
list = new List<Calısan>();
}
}
}

Categories

Resources