Deserailizing xml to C# list is empty? - c#

all deserialization works except for the lists:
(resdes is a list)
public class SearchResponse
{
// ELEMENTS
[XmlElement("ResDes")]
public ResDes resdes { get; set; }
[XmlElement("Return")]
public Return returns { get; set; }
// CONSTRUCTOR
public SearchResponse()
{}
}
this works:
<Return>
<test>0010000725</test>
</Return>
public class Return
{
// ELEMENTS
[XmlElement("test")]
public Test test{ get; set; }
}
but the list of items doesn't work it deserailizes into null
<ResDes >
<item>
<PoBox />
<City1>South Korea</City1>
<Country>SK</Country>
</item>
</ResDes >
public class ResDes
{
// ELEMENTS
[XmlArrayItem("item")]
public List<ResDesItem> ResDesItem { get; set; }
// CONSTRUCTOR
public ResDes ()
{ }
}
Resdesitem class:
[DataContract()]
public class ResDesItem
{
[XmlElement("PoBox")]
public PoBox PoBox { get; set; }
[XmlElement("City1")]
public City1 City1 { get; set; }
[XmlElement("Country")]
public EtResultDetAdritemCountry EtResultDetAdritemCountry { get; set; }
// CONSTRUCTOR
public ResDesItem()
{ }
}

*NOTE: Do not forget to add [DataMember] on each property or member of class *
If you want to do this with DataContract way, use it in the following manner:
[DataContract]
[XmlRoot("item")]
[XmlType]
public class ResDesItem
{
[XmlElement("PoBox")]
[DataMember]
public string PoBox { get; set; }
[XmlElement("City1")]
[DataMember]
public string City1 { get; set; }
[XmlElement("Country")]
[DataMember]
public string Country { get; set; }
}
and
[DataContract]
[XmlRoot("ResDes")]
[XmlType]
public class ResDes
{
[XmlElement("item")]
[DataMember]
public List<ResDesItem> ResDesItem { get; set; }
}
rest is same as prev answer by me.

You need to create two classes as:
[Serializable]
[XmlRoot("ResDes")]
[XmlType]
public class ResDes
{
[XmlElement("item")]
public List<ResDesItem> ResDesItem { get; set; }
}
and
[Serializable]
[XmlRoot("item")]
[XmlType]
public class ResDesItem
{
[XmlElement("PoBox")]
public string PoBox { get; set; }
[XmlElement("City1")]
public string City1 { get; set; }
[XmlElement("Country")]
public string Country { get; set; }
}
Then use the following code to deserialize it, as:
XmlSerializer xmlReq = new XmlSerializer(typeof(ResDes));
string xml = #"<ResDes> <item><PoBox/><City1>South Korea</City1><Country>SK</Country> </item></ResDes>";
Stream stream = new MemoryStream(Encoding.Unicode.GetBytes(xml));
var resposnseXml = (ResDes)xmlReq.Deserialize(stream);

Related

Deserializing Server returned String to JSON

I am using the SharePoint REST API to do a search. I am pulling back the JSON results and reading them as follows:
HttpWebRequest endpointRequest = (HttpWebRequest)HttpWebRequest.Create(querystring);
endpointRequest.Method = "GET";
endpointRequest.Accept = "application/json; odata=verbose";
endpointRequest.UseDefaultCredentials = true;
HttpWebResponse endpointResponse =(HttpWebResponse)endpointRequest.GetResponse();
Stream webStream = endpointResponse.GetResponseStream();
StreamReader responseReader = new StreamReader(webStream);
var results = responseReader.ReadToEnd();
This works fine, I can see the results in JSON format. So I created a class from the JSON in VS 2017 and here is the classes created from the JSON (this was done automatically with File=>Paste Special=>Paste JSON As Classes:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class SharePointRESTResults
{
public class Rootobject
{
public D d { get; set; }
}
public class D
{
public Query query { get; set; }
}
public class Query
{
public __Metadata __metadata { get; set; }
public int ElapsedTime { get; set; }
public Primaryqueryresult PrimaryQueryResult { get; set; }
public Properties1 Properties { get; set; }
public Secondaryqueryresults SecondaryQueryResults { get; set; }
public string SpellingSuggestion { get; set; }
public Triggeredrules TriggeredRules { get; set; }
}
public class __Metadata
{
public string type { get; set; }
}
public class Primaryqueryresult
{
public __Metadata1 __metadata { get; set; }
public Customresults CustomResults { get; set; }
public string QueryId { get; set; }
public string QueryRuleId { get; set; }
public object RefinementResults { get; set; }
public Relevantresults RelevantResults { get; set; }
public object SpecialTermResults { get; set; }
}
public class __Metadata1
{
public string type { get; set; }
}
public class Customresults
{
public __Metadata2 __metadata { get; set; }
public object[] results { get; set; }
}
public class __Metadata2
{
public string type { get; set; }
}
public class Relevantresults
{
public __Metadata3 __metadata { get; set; }
public object GroupTemplateId { get; set; }
public object ItemTemplateId { get; set; }
public Properties Properties { get; set; }
public object ResultTitle { get; set; }
public object ResultTitleUrl { get; set; }
public int RowCount { get; set; }
public Table Table { get; set; }
public int TotalRows { get; set; }
public int TotalRowsIncludingDuplicates { get; set; }
}
public class __Metadata3
{
public string type { get; set; }
}
public class Properties
{
public Result[] results { get; set; }
}
public class Result
{
public __Metadata4 __metadata { get; set; }
public string Key { get; set; }
public string Value { get; set; }
public string ValueType { get; set; }
}
public class __Metadata4
{
public string type { get; set; }
}
public class Table
{
public __Metadata5 __metadata { get; set; }
public Rows Rows { get; set; }
}
public class __Metadata5
{
public string type { get; set; }
}
public class Rows
{
public Result1[] results { get; set; }
}
public class Result1
{
public __Metadata6 __metadata { get; set; }
public Cells Cells { get; set; }
}
public class __Metadata6
{
public string type { get; set; }
}
public class Cells
{
public Result2[] results { get; set; }
}
public class Result2
{
public __Metadata7 __metadata { get; set; }
public string Key { get; set; }
public object Value { get; set; }
public string ValueType { get; set; }
}
public class __Metadata7
{
public string type { get; set; }
}
public class Properties1
{
public Result3[] results { get; set; }
}
public class Result3
{
public __Metadata8 __metadata { get; set; }
public string Key { get; set; }
public string Value { get; set; }
public string ValueType { get; set; }
}
public class __Metadata8
{
public string type { get; set; }
}
public class Secondaryqueryresults
{
public __Metadata9 __metadata { get; set; }
public object[] results { get; set; }
}
public class __Metadata9
{
public string type { get; set; }
}
public class Triggeredrules
{
public __Metadata10 __metadata { get; set; }
public object[] results { get; set; }
}
public class __Metadata10
{
public string type { get; set; }
}
}
}
So I now am trying to deserialize the results as follows:
SharePointRESTResults resultX = JsonConvert.DeserializeObject<SharePointRESTResults>(results());
The results I need should be in the Result2 Class. The problem I have is that this line is setting resultX = to "ConsoleApplication1.SharePointRESTResults" and nothing more. I looked in the JSON Serializing and Deserializing here: JSON Documentation but still cannot get the results into the class so I can pull out the data. I appreciate any help.
The main points are -
The Account Declaration.
JsonProperty attribute.
NOTE : If you have an object Which keys can change, Then you need to use a
Dictionary<string, T>
. A regular class won't work for that; neither will a
List<T>
.

Mapping Service Class with two Class to DTO Class with properties

I have a service Class list with two Class inside:
public class ParentClass
{
public ChildClass A { get; set; }
public ChildClass2 B { get; set; }
}
public class ChildClass
{
public int Id { get; set; }
public string Name { get; set; }
}
public class ChildClass2
{
public string Color { get; set; }
public string Nick { get; set; }
}
And I would want mapping with AutoMapper into list that have the same properties that Child's Class:
public class DTOClass
{
public int Id { get; set; }
public string Name { get; set; }
public string Color { get; set; }
public string Nick { get; set; }
}
It work fine:
My config:
Mapper.CreateMap<ChildClass, DTOClass>();
Mapper.CreateMap<ChildClass2, DTOClass>();
My code:
List<ParentClass> listParentClass = getListParentClass();
List<DTOClass> listDtoClass = new List<DTOClass>();
ParentClass dtoClass = new ParentClass();
foreach (var parentClass in listParentClass)
{
dtoClass = AutoMapper.Mapper.Map<ChildClass, DTOClass >(parentClass.A);
AutoMapper.Mapper.Map<ChildClass2, DTOClass >(parentClass.B, dtoClass);
listDtoClass.Add(dtoClass);
}
Would I like to remove the foreach, can I?
I searched about Mapping with Child's Class, Mapping with multiple Class to one Class, no success.
I tried configurate it with ForAllMembers, but not work:
Mapper.CreateMap<ParentClass, DTOClass>()
.ForAllMembers(op => op.MapFrom(s => Mapper.Map<ChildClass, DTOClass>(s.A)));
I'm not especialist into AutoMapper, if sameone could help me. I would appreciate.
You can do this:
public class ParentClass
{
public ChildClass A { get; set; }
public ChildClass2 B { get; set; }
}
public class ChildClass
{
public int Id { get; set; }
public string Name { get; set; }
}
public class ChildClass2
{
public string Color { get; set; }
public string Nick { get; set; }
}
public class DTOClass
{
public int AId { get; set; }
public string AName { get; set; }
public string BColor { get; set; }
public string BNick { get; set; }
}
Your mapping:
cfg.CreateMap<ChildClass, DTOClass>();
cfg.CreateMap<ChildClass2, DTOClass>();
cfg.CreateMap<ParentClass, DTOClass>();
Your example:
List<ParentClass> listParentClass = getListParentClass();
//List<DTOClass> listDtoClass = new List<DTOClass>();
var listDtoClass = AutoMapper.Mapper.Map<List<DTOClass>>(listParentClass);

How to Serialize to a "Collection with an Attribute" Using the XML Serializer

I have this model:
[XmlArray(ElementName = "Listing")]
[XmlArrayItem(ElementName = "Classification")]
public List<Classification> classifications { get; set; }
[XmlRoot("Listing")]
public class Classification
{
[XmlAttribute("Name")]
public string name { get; set; }
[XmlText]
public string Value { get; set; }
}
That gives me this:
<Listing>
<Classification Name="Location">AsiaPacific</Classification>
</Listing>
How should I modify my class to get this:
<Listing reference = "MyReference">
<Classification Name="Location">AsiaPacific</Classification>
</Listing>
After a few (hundreds) trial and error, I got the result that I need by modifying the model to:
[XmlElement(ElementName = "Listing")]
public ClassificationWrapper classificationWrapper { get; set; }
public class ClassificationWrapper
{
[XmlAttribute("reference")]
public string ref= "MyReference";
[XmlElement("Classification", typeof(Classification))]
public List<Classification> classifications { get; set; }
public ClassificationWrapper() { this.classifications = new List<Classification>(); }
}
public class Classification
{
[XmlAttribute("Name")]
public string name { get; set; }
[XmlText]
public string Value { get; set; }
}

Json.Net Deserialize Returning Nulls

I'm using the Petfinder API and trying to return a root object in my C# code. I used the Json class generator to generate the classes, but the Deserialize function is returning nulls.
This is my C# code:
using (var client = new WebClient())
{
var json = new WebClient().DownloadString("http://api.petfinder.com/shelter.getPets?format=json&key=<key>&id=<id>");
Petfinder deserializedPet = JsonConvert.DeserializeObject<Petfinder>(json);
}
The Petfinder object is defined as:
internal class Petfinder
{
[JsonProperty("#xmlns:xsi")]
public string XmlnsXsi { get; set; }
[JsonProperty("lastOffset")]
public LastOffset LastOffset { get; set; }
[JsonProperty("pets")]
public Pets Pets { get; set; }
[JsonProperty("header")]
public Header Header { get; set; }
[JsonProperty("#xsi:noNamespaceSchemaLocation")]
public string XsiNoNamespaceSchemaLocation { get; set; }
}
The first few lines of the json string is as follows:
{"#encoding":"iso-8859-1","#version":"1.0","petfinder":{"#xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","lastOffset":{"$t":"25"},"pets":{"pet":[{"options":{"option":[{"$t":"hasShots"},{"$t":"altered"},{"$t":"housetrained"}]},"breeds":{"breed":{"$t":"Domestic Medium Hair"}},"shelterPetId":{},"status":{"$t":"A"},"name":{"$t":"Jasmine"},...
If that helps at all.
I'm a newbie to json.net. What am I doing wrong?
Your class is wrong, take a look at the output from json2csharp.com for the example json you provided. Obviously the __invalid_name_$t needs to be manually fixed and the mapped using [JsonProperty].
public class LastOffset
{
public string __invalid_name__$t { get; set; }
}
public class Option
{
public string __invalid_name__$t { get; set; }
}
public class Options
{
public List<Option> option { get; set; }
}
public class Breed
{
public string __invalid_name__$t { get; set; }
}
public class Breeds
{
public Breed breed { get; set; }
}
public class ShelterPetId
{
}
public class Status
{
public string __invalid_name__$t { get; set; }
}
public class Name
{
public string __invalid_name__$t { get; set; }
}
public class Pet
{
public Options options { get; set; }
public Breeds breeds { get; set; }
public ShelterPetId shelterPetId { get; set; }
public Status status { get; set; }
public Name name { get; set; }
}
public class Pets
{
public List<Pet> pet { get; set; }
}
public class Petfinder
{
public string __invalid_name__#xmlns:xsi { get; set; }
public LastOffset lastOffset { get; set; }
public Pets pets { get; set; }
}
public class RootObject
{
public string __invalid_name__#encoding { get; set; }
public string __invalid_name__#version { get; set; }
public Petfinder petfinder { get; set; }
}

Json object return from YouTube for duplicated fields

I have the following C# code for Json taken from YouTube Link, which has two properties with same name i.e author, author2 and inside author - name, uri (Which I changed to Uris Since it is a Keyword) On call the url it returns everything but not author, It shows null for author, help me fixing this
Here is my source code,
[DataContract]
public class Title
{
[DataMember (Name="$t")]
public string title { get; set; }
}
[DataContract]
public class Name2
{
[DataMember(Name = "$t")]
public string authorname { get; set; }
}
[DataContract]
public class Uri2
{
[DataMember(Name = "$t")]
public string channelurl { get; set; }
}
public class Author2
{
public Name2 name { get; set; }
public Uri2 uri { get; set; }
}
[DataContract]
public class YtChannelId
{
[DataMember (Name="$t")]
public string channelid { get; set; }
}
[DataContract]
public class MediaThumbnail
{
[DataMember(Name = "url")]
public string imgurl { get; set; }
}
[DataContract]
public class MediaGroup
{
[DataMember (Name="media$thumbnail")]
public List<MediaThumbnail> media_thumbnail { get; set; }
}
[DataContract]
public class FeAEntry
{
public List<Author2> author { get; set; }
[DataMember (Name="yt$channelId")]
public YtChannelId channelId { get; set; }
public Title title { get; set; }
[DataMember (Name="media$group")]
public MediaGroup media_group { get; set; }
}
public class FeAFeed
{
public List<FeAEntry> entry { get; set; }
}
public class Name
{
[DataMember (Name="$t")]
public string t { get; set; }
}
public class Uris
{
[DataMember (Name="$t")]
public string t { get; set; }
}
public class Author
{
public Name name { get; set; }
public Uris uri { get; set; }
}
public class FeARootObject
{
public FeAFeed feed { get; set; }
public List<Author> author { get; set; }
}
Regards,
Siva
You didn't assign the [DataMember] attribute to the author property. Only DataMembers are serialized by WCF.
Your Author2 class is also missing the [DataContract] attribute.
See: http://msdn.microsoft.com/en-us/library/ms733127.aspx

Categories