LDAP SearchResponse to Json C# - 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() { }

Related

Parse JSon List from webapi [frombody]

I have a json array that comes from webapi [fromBody].
my class is something like this:
public class SalesBOMComponent
{
public string BILLOFMATERIAL { get; set; }
public string BOMITEMNODENUMBER { get; set; }
public string BOMCOMPONENT { get; set; }
public string BOMCOMPONENTDESCRIPTION { get; set; }
public string COMPONENTQUANTITY { get; set; }
public string COMPONENTUOM { get; set; }
public string INDICATORSPAREPART { get;set; }
}
public class SalesBOM
{
public string BILLOFMATERIAL { get; set; }
public string MATERIALPARENT { get; set; }
public string PLANT { get; set; }
public string BOMUSAGE { get; set; }
public string ALTERNATIVEBOM { get; set; }
public string VALIDDATE { get; set; }
public string BASEQTYPARENT { get; set; }
public string BASEUOMPARENT { get; set; }
public string BOMSTATUS { get; set; }
public List<SalesBOMComponent> BOMCOMPONENTS { get; set; }
}
public class Product
{
public string MATERIALPARENT { get; set; }
public string DESCRIPTION { get; set; }
public List<SalesBOM> BOMSALES { get; set; }
}
I would like to get value from BOMCOMPONENT (under class SalesBOMComponent) and Plant (under class SalesBOM).
however, the method read from [fromBody] using c#
public HttpResponseMessage Post([FromBody] Product inputdata)
{
string result = string.Empty;
string currentDate = string.Empty;
string ErrorMessage = string.Empty;
string MaterialParent = string.Empty;
string MaterialDescription = string.Empty;
MaterialParent = inputdata.MATERIALPARENT;
MaterialDescription = inputdata.DESCRIPTION;
how to achieve that?

Deserializing the JSON Objest results in all null fields C#

My jsonResponse is something like this:
{"status":200,"data":{"first_name":"\u062e\u0633","last_name":"\u0635\u062f\u0627","national_code":"1","image_photo":"1.jpg","cellphone":"1234","city":{"id":1,"name":"x","created_at":"2017-02-27 17:54:44","updated_at":"2017-02-27 17:54:44"},"email":"something#gmail.com","even_odd":1,"Register Time":"2018-01-25 10:39:17","is_blocked":false,"receive_regular_offer":"false","level":1,"ride_count":0,"service_type":1,"bank":"\u0645","iban":"xy","card_number":"","holder":"\u062e\u0633","plate_number":"123","vehicle_model":"\u067e\u0698","vehicle_color":"\u062a\u0627\u06a9\u0633","unique_id":592875}}
I have created a class like this:
public class Driver
{
public string first_name { get; set; }
public string last_name { get; set; }
public string national_code { get; set; }
public string image_photo { get; set; }
public string cellphone { get; set; }
public string city { get; set; }
public string email { get; set; }
public string even_odd { get; set; }
public bool is_blocked { get; set; }
public bool receive_regular_offer { get; set; }
public string level { get; set; }
public string ride_count { get; set; }
public string service_type { get; set; }
public string bank { get; set; }
public string iban { get; set; }
public string card_number { get; set; }
public string holder { get; set; }
public string vehicle_model { get; set; }
public string vehicle_color { get; set; }
public string unique_id { get; set; }
}
and used this:
jsonResponse = reader.ReadToEnd();
JavaScriptSerializer js = new JavaScriptSerializer();
Driver snappDriver = js.Deserialize<Driver>(jsonResponse);
But the result is all null!
1.your class should be defined right
example:
void Main()
{
var json =api();
//dynamic
var dynamic_json = JsonConvert.DeserializeObject(json).Dump() as JObject;
//strong type
var strong_Type_json = JsonConvert.DeserializeObject<Driver>(json).Dump() ;
}
string api(){
return #"
{""status"":200,""data"":{""first_name"":""\u062e\u0633"",""last_name"":""\u0635\u062f\u0627"",""national_code"":""1"",""image_photo"":""1.jpg"",""cellphone"":""1234"",""city"":{""id"":1,""name"":""x"",""created_at"":""2017-02-27 17:54:44"",""updated_at"":""2017-02-27 17:54:44""},""email"":""something#gmail.com"",""even_odd"":1,""Register_Time"":""2018-01-25 10:39:17"",""is_blocked"":false,""receive_regular_offer"":""false"",""level"":1,""ride_count"":0,""service_type"":1,""bank"":""\u0645"",""iban"":""xy"",""card_number"":"""",""holder"":""\u062e\u0633"",""plate_number"":""123"",""vehicle_model"":""\u067e\u0698"",""vehicle_color"":""\u062a\u0627\u06a9\u0633"",""unique_id"":592875}}
";
}
public class City
{
public int id { get; set; }
public string name { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
}
public class Data
{
public string first_name { get; set; }
public string last_name { get; set; }
public string national_code { get; set; }
public string image_photo { get; set; }
public string cellphone { get; set; }
public City city { get; set; }
public string email { get; set; }
public int even_odd { get; set; }
public string Register_Time { get; set; }
public bool is_blocked { get; set; }
public string receive_regular_offer { get; set; }
public int level { get; set; }
public int ride_count { get; set; }
public int service_type { get; set; }
public string bank { get; set; }
public string iban { get; set; }
public string card_number { get; set; }
public string holder { get; set; }
public string plate_number { get; set; }
public string vehicle_model { get; set; }
public string vehicle_color { get; set; }
public int unique_id { get; set; }
}
public class Driver
{
public int status { get; set; }
public Data data { get; set; }
}
2.json's key Register Time in strong type is invalid name
you can add _ in your json string to solve the problem
Try to create exactly the same class definition as your json has. Your Driver class describes json object's data property.
public class DriverWrapper
{
public string status { get; set; }
public Driver data { get; set; }
}
You have to create another object class that handles status and data property
try this
Create a class Response
class Response{
public int status { get; set;}
public Driver data { get; set;}
}
and do it this way
jsonResponse = reader.ReadToEnd();
JavaScriptSerializer js = new JavaScriptSerializer();
Response snappDriver = js.Deserialize<Response>(jsonResponse);

Why my deserialization is giving me an error Newtonsoft.Json.JsonConvert?

public List<CoinMarket> GetCoinMarket()
{
List<CoinMarket> coinMarket = new List<CoinMarket>();
var URLWebAPI = "http://190.202.54.19/wsZeus/api/Account/Markets/Get";
try
{
using (var Client = new System.Net.Http.HttpClient())
{
var JSON = Client.GetStringAsync(URLWebAPI);
coinMarket = (List<CoinMarket>)Newtonsoft.Json.JsonConvert.DeserializeObject(JSON.Result);
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(#" ERROR {0}", ex.Message);
}
return coinMarket;
}
It is throwing and i do not know why. It looks like there is something wrong with the serialization part. But i verified it.
You are using json deserializer incorrectly. DeserializeObject returns custom object which is not castable to your List<T>. This output:
Newtonsoft.Json.Linq.JArray
SO20171129.CoinData[]
System.Collections.Generic.List`1[SO20171129.CoinData]
is the result of this code.
class Program
{
static void Main(string[] args)
{
// returns Newtonsoft.Json.Linq.JArray
var coinMarket = Newtonsoft.Json.JsonConvert.DeserializeObject(File.ReadAllText("get.json"));
Console.WriteLine(coinMarket.GetType());
// returns array of CoinData
var coinMarketTyped = Newtonsoft.Json.JsonConvert.DeserializeObject<CoinData[]>(File.ReadAllText("get.json"));
Console.WriteLine(coinMarketTyped.GetType());
// returns List of CoinData
var coinMarketTyped2 = Newtonsoft.Json.JsonConvert.DeserializeObject<List<CoinData>>(File.ReadAllText("get.json"));
Console.WriteLine(coinMarketTyped2.GetType());
}
}
public class CoinData
{
public string id { get; set; }
public string name { get; set; }
public string symbol { get; set; }
public string rank { get; set; }
public string price_usd { get; set; }
public string price_btc { get; set; }
public string __invalid_name__24h_volume_usd { get; set; }
public string market_cap_usd { get; set; }
public string available_supply { get; set; }
public string total_supply { get; set; }
public string percent_change_1h { get; set; }
public string percent_change_24h { get; set; }
public string percent_change_7d { get; set; }
public string last_updated { get; set; }
}
My guess is that your json structure members do not match the CoinMarket class members.
What I would do is to copy the json result and generate the corresponding CoinMarket class on the following website: http://json2csharp.com/
It will output the right CoinMarket class for you.
public class CoinMarket
{
public string id { get; set; }
public string name { get; set; }
public string symbol { get; set; }
public string rank { get; set; }
public string price_usd { get; set; }
public string price_btc { get; set; }
[JsonProperty("24h_volume_usd")]
public string h_volume_usd { get; set; }
public string market_cap_usd { get; set; }
public string available_supply { get; set; }
public string total_supply { get; set; }
public string percent_change_1h { get; set; }
public string percent_change_24h { get; set; }
public string percent_change_7d { get; set; }
public string last_updated { get; set; }
}
}
This is my CoinMarket Class

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...)

Convert Json Http request to c# obj

I`m new in programming winodws 8 app , i have a webservice when i try to connect it using httprequest (Using URL with variables), this service return this:
{"d":"{\"sessionid\":\"twzv50okccwvgggeesjje2wa\",\"VersionInfo\":{\"Rel\":0,\"Ver\":0,\"Patch\":0,\"ForceUpdate\":0,\"UpdateType\":0,\"Globals\":{\"MultiSessionsAllowed\":true,\"CommCalcType\":2,\"PriceChangedTimer\":25,\"ValidLotsLocation\":2,\"CustumizeTradeMsg\":false,\"FirstWhiteLabeledOffice\":null,\"DealerTreePriv\":0,\"ClientConnectTimer\":200,\"ClientTimeoutTimer\":500,\"DefaultLots\":0.01,\"WebSecurityID\":\"agagag\",\"ServerGMT\":3}},\"SystemLockInfo\":{\"MinutesRemaining\":0,\"HoursRemaining\":0,\"DaysRemaining\":0,\"Maintanance\":0,\"WillBeLocked\":1},\"FirstWhiteLabel\":\"VertexFX 10\",\"WLID\":\"3\",\"CheckWhiteLabel\":true,\"Password\":\"1444\",\"Username\":\"test\",\"LastTickTime\":\"\/Date(1396307573431)\/\",\"SelectedAccount\":78821860,\"Name\":0,\"ServicePath\":null,\"GWSessionID\":\"56630\",\"IP\":\"Web (212.35.90.211)\",\"SessionDateStart\":\"01/04/2014 02:12:53\",\"CompanyName\":\"Hybrid Solutions\",\"UserId\":6119,\"DemoClient\":\"0\",\"FName\":\"omqrstu\",\"SName\":\"\",\"TName\":\"\",\"LName\":\"\",\"Sms\":null,\"isReadOnly\":\"0\",\"SchSms\":\"2\",\"AlertSms\":\"2\",\"Temp\":null,\"GMTOffset\":\"2\",\"SvrGMT\":\"3\",\"ClientType\":null,\"EnableNews\":\"1\",\"PublicSlideNews\":\"\",\"PrivateSlideNews\":\"Welcome to V 10\",\"DealerTreePriv\":1}"}
i have simple windows app with one button when i click the button i send the url with variables and i got the obj above , i want to use content of this object like UserID in if statement but with no vain i dont know how to use it in C# , can and body help me??
I use this code. I know it has many errors but I need someone guide me.
private void Button_Click(object sender, RoutedEventArgs e)
{
String uriString = "url";
var uri = new Uri(uriString);
var httpWebRequest = HttpWebRequest.Create(uri);
httpWebRequest.BeginGetResponse(new AsyncCallback(OnGettingResponse), httpWebRequest);
}
private void OnGettingResponse(IAsyncResult ar)
{
var outerRoot = JsonConvert.DeserializeObject<OuterRootObject>( json );
var root = JsonConvert.DeserializeObject<RootObject>( outerRoot.d );
MessageBox.Show(root.UserId);
}
This is kind of a nasty situation. What you're getting back is a JSON object with a single property (i.e. d) and that property contains a string of JSON. So you basically need to unwrap the inner JSON from it's envelope. The following classes/code should work (using JSON.NET to do the deserialization).
public class OuterRootObject
{
public string d { get; set; }
}
public class Globals
{
public bool MultiSessionsAllowed { get; set; }
public int CommCalcType { get; set; }
public int PriceChangedTimer { get; set; }
public int ValidLotsLocation { get; set; }
public bool CustumizeTradeMsg { get; set; }
public object FirstWhiteLabeledOffice { get; set; }
public int DealerTreePriv { get; set; }
public int ClientConnectTimer { get; set; }
public int ClientTimeoutTimer { get; set; }
public double DefaultLots { get; set; }
public string WebSecurityID { get; set; }
public int ServerGMT { get; set; }
}
public class VersionInfo
{
public int Rel { get; set; }
public int Ver { get; set; }
public int Patch { get; set; }
public int ForceUpdate { get; set; }
public int UpdateType { get; set; }
public Globals Globals { get; set; }
}
public class SystemLockInfo
{
public int MinutesRemaining { get; set; }
public int HoursRemaining { get; set; }
public int DaysRemaining { get; set; }
public int Maintanance { get; set; }
public int WillBeLocked { get; set; }
}
public class RootObject
{
public string sessionid { get; set; }
public VersionInfo VersionInfo { get; set; }
public SystemLockInfo SystemLockInfo { get; set; }
public string FirstWhiteLabel { get; set; }
public string WLID { get; set; }
public bool CheckWhiteLabel { get; set; }
public string Password { get; set; }
public string Username { get; set; }
public DateTime LastTickTime { get; set; }
public int SelectedAccount { get; set; }
public int Name { get; set; }
public object ServicePath { get; set; }
public string GWSessionID { get; set; }
public string IP { get; set; }
public string SessionDateStart { get; set; }
public string CompanyName { get; set; }
public int UserId { get; set; }
public string DemoClient { get; set; }
public string FName { get; set; }
public string SName { get; set; }
public string TName { get; set; }
public string LName { get; set; }
public object Sms { get; set; }
public string isReadOnly { get; set; }
public string SchSms { get; set; }
public string AlertSms { get; set; }
public object Temp { get; set; }
public string GMTOffset { get; set; }
public string SvrGMT { get; set; }
public object ClientType { get; set; }
public string EnableNews { get; set; }
public string PublicSlideNews { get; set; }
public string PrivateSlideNews { get; set; }
public int DealerTreePriv { get; set; }
}
var outerRoot = JsonConvert.DeserializeObject<OuterRootObject>( json );
var root = JsonConvert.DeserializeObject<RootObject>( outerRoot.d );

Categories

Resources