Difference JSON deserialisation 'online site' vs 'paste into Visual studio' - c#

I try to generate C# class with JSON datas. This datas are on this site
Method 1 : I used this online builder builder online
Method 2 : I used special paste to JSON into Visual Studio 2015 (like explain here)
Conclusion: not same result! Why?
Result with online site :
public class Translations
{
public string de { get; set; }
public string es { get; set; }
public string fr { get; set; }
public string ja { get; set; }
public string it { get; set; }
}
public class RootObject
{
public string name { get; set; }
public List<string> topLevelDomain { get; set; }
public string alpha2Code { get; set; }
public string alpha3Code { get; set; }
public List<object> callingCodes { get; set; }
public string capital { get; set; }
public List<object> altSpellings { get; set; }
public string relevance { get; set; }
public string region { get; set; }
public string subregion { get; set; }
public int population { get; set; }
public List<object> latlng { get; set; }
public string demonym { get; set; }
public double? area { get; set; }
public double? gini { get; set; }
public List<string> timezones { get; set; }
public List<object> borders { get; set; }
public string nativeName { get; set; }
public string numericCode { get; set; }
public List<string> currencies { get; set; }
public List<object> languages { get; set; }
public Translations translations { get; set; }
}
Result with special paste of Visual Studio :
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public string name { get; set; }
public string[] topLevelDomain { get; set; }
public string alpha2Code { get; set; }
public string alpha3Code { get; set; }
public string[] callingCodes { get; set; }
public string capital { get; set; }
public string[] altSpellings { get; set; }
public string relevance { get; set; }
public string region { get; set; }
public string subregion { get; set; }
public int population { get; set; }
public float?[] latlng { get; set; }
public string demonym { get; set; }
public float? area { get; set; }
public float? gini { get; set; }
public string[] timezones { get; set; }
public string[] borders { get; set; }
public string nativeName { get; set; }
public string numericCode { get; set; }
public string[] currencies { get; set; }
public string[] languages { get; set; }
public Translations translations { get; set; }
}
public class Translations
{
public string de { get; set; }
public string es { get; set; }
public string fr { get; set; }
public string ja { get; set; }
public string it { get; set; }
}
Worse! The deserialisation with VS code does'nt work!
Code for deserialise :
string url = #"http://restcountries.eu/rest/v1";
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(IEnumerable<Rootobject>));
WebClient syncClient = new WebClient();
string content = syncClient.DownloadString(url);
using (MemoryStream memo = new MemoryStream(Encoding.Unicode.GetBytes(content)))
{
IEnumerable<Rootobject> countries = (IEnumerable<Rootobject>)serializer.ReadObject(memo);
int i = countries.Count();
}
Console.Read();
Have you an idea of this difference? Bug VS?

In the second example, Visual Studio actually wraps the "root object" with yet another root object that contains an array of Class1.
Since the payload data structure root is an array, not an object, this would appear to be a bug, provided you used the correct payload to generate the structure.
As a result, just replace Rootobject references with Class1.
string url = #"http://restcountries.eu/rest/v1";
DataContractJsonSerializer serializer =
new DataContractJsonSerializer(typeof(IEnumerable<Class1>));
WebClient syncClient = new WebClient();
string content = syncClient.DownloadString(url);
using (MemoryStream memo = new MemoryStream(Encoding.Unicode.GetBytes(content)))
{
IEnumerable<Class1> countries = (IEnumerable<Class1>)serializer.ReadObject(memo);
int i = countries.Count();
}
Console.Read();
As an aside, you should really switch to a more modern serializer such as Newtonsoft JSON.NET.

Related

C# MVC can't Deserialize a tuple

I have a Json model that looks like this
private class SearchMetadataJson
{
public string entertain { get; set; }
public string master { get; set; }
public string memail { get; set; }
public string key { get; set; }
public (int, string)[] mood { get; set; }
public int? soundnumber { get; set; }
public int? ftv { get; set; }
public int? com { get; set; }
public (int, string)[] sims { get; set; }
public (int, string)[] keysecond { get; set; }
public string popt { get; set; }
public (string, string) syncs { get; set; }
}
And I try to de-serialize the object like this
var CommentObj = JsonSerializer.Deserialize<SearchMetadataJson>(CommentAsString);
The data that I'm trying to de-serialize (aka "CommentAsString") looks like this
"{\"entertain\":\"PEG\",\"master\":\"Phos Ent Group\",\"memail\":\"example#example.com\",\"key\":\"Db\",\"mood\":{\"1\":\"TypeA\",\"4\":\"TypeB\",\"5\":\"TypeC\"},\"soundnumber\":\"5\",\"ftv\":\"4\",\"com\":\"3\",\"sims\":{\"1\":\"Band1\",\"2\":\"Band2\"},\"keysecond\":{\"1\":\"KeyWord1\",\"2\":\"KeyWord2\",\"3\":\"KeyWord3\"},\"syncs\":{\"Other pubber\":\"example2#example.com\"}}"
But I keep getting this error
Does anyone see what the problem is?
Update
The integers in CommentAsString are variables and will be different every time the function is called so I can't make a Json Object that has a key value of a particular integer.
Let's look at the actual formatted data structure
{
"entertain":"PEG",
"master":"Phos Ent Group",
"memail":"example#example.com",
"key":"Db",
"mood":{
"1":"TypeA",
"4":"TypeB",
"5":"TypeC"
},
"soundnumber":"5",
"ftv":"4",
"com":"3",
"sims":{
"1":"Band1",
"2":"Band2"
},
"keysecond":{
"1":"KeyWord1",
"2":"KeyWord2",
"3":"KeyWord3"
},
"syncs":{
"Other pubber":"example2#example.com"
}
}
Converting these to an array of tuple would be unusual. What you seemingly have are dictionary's
Example
private class SearchMetadataJson
{
public string entertain { get; set; }
public string master { get; set; }
public string memail { get; set; }
public string key { get; set; }
public Dictionary<int,string> mood { get; set; }
public int? soundnumber { get; set; }
public int? ftv { get; set; }
public int? com { get; set; }
public Dictionary<int,string> sims { get; set; }
public Dictionary<int,string> keysecond { get; set; }
public string popt { get; set; }
// public (string, string) syncs { get; set; }
}
It's debatable whether the last property is an object or another dictionary as well.
"syncs":{
"Other pubber":"example2#example.com"
}
However, I'll leave that up to you.
your have error in the model, use this site for convert your json in c#
https://json2csharp.com/
// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
public class Mood {
public string _1 { get; set; }
public string _4 { get; set; }
public string _5 { get; set; }
}
public class Sims {
public string _1 { get; set; }
public string _2 { get; set; }
}
public class Keysecond {
public string _1 { get; set; }
public string _2 { get; set; }
public string _3 { get; set; }
}
public class Syncs {
public string Otherpubber { get; set; }
}
public class Root {
public string entertain { get; set; }
public string master { get; set; }
public string memail { get; set; }
public string key { get; set; }
public Mood mood { get; set; }
public string soundnumber { get; set; }
public string ftv { get; set; }
public string com { get; set; }
public Sims sims { get; set; }
public Keysecond keysecond { get; set; }
public Syncs syncs { get; set; }
}
try again with using this
first read your string
this is the response using post, get or delete
var response = await client.PostAsync("your-url", datasBody);
var contentData = await response.Content.ReadAsStringAsync();
var options = new JsonSerializerOptions() { PropertyNameCaseInsensitive = true };
var CommentObj = JsonSerializer.Deserialize<Root>(contentData, options);
if your model is bad or not match using
[JsonProperty("entertain")]
public string entertain { get; set; }
You will either need to use a custom converter or convert your tuples into separate classes with fields to explain what each field is used for.

LDAP SearchResponse to Json C#

I am using a C# LdapConnection to get a SearchResponse at work. I can get the SearchResponse into a Json string, but am unable to put that Json string into an object class with properties which mimic the SearchResponse. The Json string is properly formatted. Am I using the Newtonsoft.Json library in the wrong way? Is there a better way to do this? My only requirements are that I get a SearchResponse into my object class (DirectoryEntity) so I can use it from there.
My Console Application:
class Program
{
static void Main(string[] args)
{
LdapClient client = new LdapClient();
List<LdapSearchResponseModel> list = new List<LdapSearchResponseModel>();
string query = "(|(uupid=name1)(uupid=name2))";
string[] attributes = new string[] { };
string host = "id.directory.univ";
int port = 1234;
SearchResponse response = client.RawQuery(query, attributes, host, port);
string json = JsonConvert.SerializeObject(response);
var test = JsonConvert.DeserializeObject<DirectoryEntities>(json);
}
}
My DirectoryEntity Class:
public class DirectoryEntity
{
public string EntityDN { get; set; }
public int MailStop { get; set; }
public List<string> UniversityAffiliation { get; set; }
public int UniversityId { get; set; }
public string GivenName { get; set; }
public string Title { get; set; }
public string PasswordState { get; set; }
public string MiddleName { get; set; }
public string AccountState { get; set; }
public int Uid { get; set; }
public string Mail { get; set; }
public string MailPreferredAddress { get; set; }
public DateTime DateOfBirth { get; set; }
public List<string> GroupMembership { get; set; }
public string DegreeType { get; set; }
public int ClassLevelCode { get; set; }
public string AuthId { get; set; }
public string Major { get; set; }
public string ClassLevel { get; set; }
public bool SupressDisplay { get; set; }
public string UnderGraduateLevel { get; set; }
public string ObjectClass { get; set; }
public int DepartmentNumber { get; set; }
public List<string> EduPersonAffiliation { get; set; }
public string LocalPostalAddress { get; set; }
public string Uupid { get; set; }
public string LocalPhone { get; set; }
public string TelephoneNumber { get; set; }
public string Department { get; set; }
public string Sn { get; set; }
}
My DirectoryEntities Class:
public class DirectoryEntities
{
public List<DirectoryEntity> Entities { get; set; }
public int Count { get; set; }
}
Have you tried explicitly defining a default constructor for the DirectoryEntity class? I believe that Newtonsoft requires objects to have a default constructor before they can be deserialized. Try adding this to the DirectoryEntity class:
public DirectoryEntity() { }

JsonConvert.DeserializeObject not working sometimes

I'm trying to Deserialize some json using JsonConver.DeserializeObject. however it's not working on some json from the api I'm using. here is a link that does not work: https://api.pokemontcg.io/v1/cards?setCode=smp
and here is a link that does work. https://api.pokemontcg.io/v1/cards?setCode=sm2
I'm not sure why it sometimes works and sometimes not. The data that comes out of it is very similar to each other, just different cards.
Here is the code:
public static async Task<T> GetDataAsync<T>(this HttpClient client, string address, string querystring)
where T : class
{
var uri = address;
if (!string.IsNullOrEmpty(querystring))
{
uri += querystring;
}
var httpMessage = await client.GetStringAsync(uri);
var jsonObject = JsonConvert.DeserializeObject<T>(httpMessage);
return jsonObject;
}
Now my card class
namespace CardAppReal.Lib.Models
{
public class Card
{
public string id { get; set; }
public string name { get; set; }
public string imageUrl { get; set; }
public string imageUrlHiRes { get; set; }
public string supertype { get; set; } // if pokemon, trainer or energy
public string setcode { get; set; }
public int number { get; set; }
public string set { get; set; }
}
}
With a root
using System.Collections.Generic;
using CardAppReal.Lib.Models;
namespace CardAppReal.Lib.Entities
{
public class RootCard
{
public List<Card> cards { get; set; }
}
}
If u could help me out I would find it amazing.
I have tested your json.
this is the Model
namespace Test
{
public class Attack
{
public List<string> cost { get; set; }
public string name { get; set; }
public string text { get; set; }
public string damage { get; set; }
public int convertedEnergyCost { get; set; }
}
public class Weakness
{
public string type { get; set; }
public string value { get; set; }
}
public class Resistance
{
public string type { get; set; }
public string value { get; set; }
}
public class Ability
{
public string name { get; set; }
public string text { get; set; }
public string type { get; set; }
}
public class Card
{
public string id { get; set; }
public string name { get; set; }
public int nationalPokedexNumber { get; set; }
public string imageUrl { get; set; }
public string imageUrlHiRes { get; set; }
public string subtype { get; set; }
public string supertype { get; set; }
public string hp { get; set; }
public List<string> retreatCost { get; set; }
public string number { get; set; }
public string artist { get; set; }
public string rarity { get; set; }
public string series { get; set; }
public string set { get; set; }
public string setCode { get; set; }
public List<string> types { get; set; }
public List<Attack> attacks { get; set; }
public List<Weakness> weaknesses { get; set; }
public List<Resistance> resistances { get; set; }
public string evolvesFrom { get; set; }
public Ability ability { get; set; }
public List<string> text { get; set; }
}
public class RootObject
{
public List<Card> cards { get; set; }
}
}
And this is how I call the Deserialize
RootObject root = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(RootObject.WRONG_JSON);
(NB WRONG_JSON is your json string...)

GeoJson c# example parse countries in the world and generate Geojson for each country

Looking for an example of how to parse / deserialize Geojson files using geojson.net. for some reason there are no examples of how to use the geojson.net package.
I would like to use this on my site with the google maps api. currently I use polygon shapes but want to move towards using geojson objects for the layers as this seems to be a better format.
using c# I would like to serialize Geojson, select specific country borders and generate a new geojson file that can be references and added to google maps as a layer.
to test this I created a colsole app to try to deserilaize the GeoJson, this does not work (please could you give me some direction on the correct way to deserialize Geojson ?)
static void Main(string[] args)
{
string Jsonstring = File.ReadAllText("c:/worldborders.json");
JavaScriptSerializer ser = new JavaScriptSerializer();
List<GeoJsonProperties> ns = (List<GeoJsonProperties>)ser.Deserialize(Jsonstring, typeof(List<GeoJsonProperties>));
?ns is Empty?
}
I created a class for the geojson file using the online generator http://json2csharp.com/ (I had thought that GeoJson.net would include the class as its a standard) , GeoJsonProperties,
public class GeoJsonProperties
{
public int scalerank { get; set; }
public string featurecla { get; set; }
public double labelrank { get; set; }
public string sovereignt { get; set; }
public string sov_a3 { get; set; }
public double adm0_dif { get; set; }
public double level { get; set; }
public string type { get; set; }
public string admin { get; set; }
public string adm0_a3 { get; set; }
public double geou_dif { get; set; }
public string geounit { get; set; }
public string gu_a3 { get; set; }
public double su_dif { get; set; }
public string subunit { get; set; }
public string su_a3 { get; set; }
public double brk_diff { get; set; }
public string name { get; set; }
public string name_long { get; set; }
public string brk_a3 { get; set; }
public string brk_name { get; set; }
public object brk_group { get; set; }
public string abbrev { get; set; }
public string postal { get; set; }
public string formal_en { get; set; }
public string formal_fr { get; set; }
public string note_adm0 { get; set; }
public string note_brk { get; set; }
public string name_sort { get; set; }
public string name_alt { get; set; }
public double mapcolor7 { get; set; }
public double mapcolor8 { get; set; }
public double mapcolor9 { get; set; }
public double mapcolor13 { get; set; }
public double pop_est { get; set; }
public double gdp_md_est { get; set; }
public double pop_year { get; set; }
public double lastcensus { get; set; }
public double gdp_year { get; set; }
public string economy { get; set; }
public string income_grp { get; set; }
public double wikipedia { get; set; }
public object fips_10 { get; set; }
public string iso_a2 { get; set; }
public string iso_a3 { get; set; }
public string iso_n3 { get; set; }
public string un_a3 { get; set; }
public string wb_a2 { get; set; }
public string wb_a3 { get; set; }
public double woe_id { get; set; }
public string adm0_a3_is { get; set; }
public string adm0_a3_us { get; set; }
public double adm0_a3_un { get; set; }
public double adm0_a3_wb { get; set; }
public string continent { get; set; }
public string region_un { get; set; }
public string subregion { get; set; }
public string region_wb { get; set; }
public double name_len { get; set; }
public double long_len { get; set; }
public double abbrev_len { get; set; }
public double tiny { get; set; }
public double homepart { get; set; }
}
public class Geometry
{
public string type { get; set; }
public List<List<List<object>>> coordinates { get; set; }
}
public class Feature
{
public string type { get; set; }
public GeoJsonProperties properties { get; set; }
public Geometry geometry { get; set; }
}
public class RootObject
{
public string type { get; set; }
public List<Feature> features { get; set; }
}
}
GeoJSON.Net works with Newtonsoft.Json. you can deserialize the same way you would using that library.
var geoJsonObject = JsonConvert.DeserializeObject<Point>(json);
For deserializing a FeatureCollection object (like the one you mention in the question) using the GeoJSON.Net library use the following code :
var collection = JsonConvert.DeserializeObject<FeatureCollection>(json);

Json response with several tables(?)

How do I parse a Json response in form of:
www.extradelar.se/match
If I understand this response right, its an array of three responses, how do I parse them in this case? How do I Deserialize this into my RootObject?
I am not sure if its due to copy paste but the json provided was not valid:
Using http://jsonlint.com/ you can validate an indent your json:
Once you indent, it is easier to look at .
The above JSON is array of array where each one contains an object.
It is a little odd for usual JSON, but maybe you have your own reasons.
Using libraries like JSON.net you can easily parse that data into C# objects.
Hope this helps
EDIT:
POCO Class:
public class RootObject
{
public string match_id { get; set; }
public string no_repick { get; set; }
public string no_agi { get; set; }
public string drp_itm { get; set; }
public string no_timer { get; set; }
public string rev_hs { get; set; }
public string no_swap { get; set; }
public string no_int { get; set; }
public string alt_pick { get; set; }
public string veto { get; set; }
public string shuf { get; set; }
public string no_str { get; set; }
public string no_pups { get; set; }
public string dup_h { get; set; }
public string ap { get; set; }
public string br { get; set; }
public string em { get; set; }
public string cas { get; set; }
public string rs { get; set; }
public string nl { get; set; }
public string officl { get; set; }
public string no_stats { get; set; }
public string ab { get; set; }
public string hardcore { get; set; }
public string dev_heroes { get; set; }
public string verified_only { get; set; }
public string gated { get; set; }
}
JSON.NET
private string getMatchId()
{
using (var webClient = new System.Net.WebClient())
{
const string url = #"http://www.extradelar.se/match";
var json = webClient.DownloadString(url);
var matchen = JsonConvert.DeserializeObject<List<List<RootObject>>>(json);
var matchId = matchen[0][0].match_id;
return matchId;
}
}

Categories

Resources