Parse JSon List from webapi [frombody] - c#

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?

Related

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

Why is "var update" unreachable code. What Can i do to get multiple returnOk statements working?

Is there a problem for me to use two return Ok statements in one If
statement? i am returning Create and update from a class called PardotUtilites and Create returns me an Id. And Update should return first name, email and phone number after editing.
namespace GSWebAPI.Controllers
{
public class CampainProspectsController : ApiController
{
[HttpPost]
public IHttpActionResult Post([FromBody] JToken Value)
{
string tocreate = "";
//string toupdate = "";
Prospects res = new Prospects();
res.Error = "";
res.Status = "";
var results = JsonConvert.DeserializeObject<Prospects>(Value.ToString());
if (results != null)
{
// results
results.id = Guid.NewGuid().ToString();
tocreate = "first_name=" + results.first_name + "&last_name=" + results.last_name + "&email=" + results.email + "&phone=" + results.phone + "&id=" + results.id;
var idstr = PardotUtilities.Create(tocreate);
return Ok(idstr);
// Error here "unreachable code"
var update = PardotUtilities.Update(tocreate, results.id);
return Ok(update);
PardotUtilities.Upsert(tocreate, results.id);
PardotUtilities.Query(tocreate, results.id);
PardotUtilities.Delete(tocreate, results.id);
// return Ok(update);
}
return Ok();
}
//public class
public class Prospects
{
public String Status { get; set; }
public String Error { get; set; }
public string id { get; set; }
public string email { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string password { get; set; }
public string company { get; set; }
public string website { get; set; }
public string job_title { get; set; }
public string department { get; set; }
public string contry { get; set; }
public string address_one { get; set; }
public string address_two { get; set; }
public string city { get; set; }
public string state { get; set; }
public string territory { get; set; }
public string zip { get; set; }
public string phone { get; set; }
public string fax { get; set; }
public string source { get; set; }
public string annual_revenue { get; set; }
public string employees { get; set; }
public string industry { get; set; }
public string years_in_business { get; set; }
public string comments { get; set; }
public string notes { get; set; }
public string score { get; set; }
public string grade { get; set; }
public string last_activity_at { get; set; }
public string recent_interaction { get; set; }
public string crm_lead_fid { get; set; }
public string crm_contact_fid { get; set; }
public string crm_owner_fid { get; set; }
public string crm_account_fid { get; set; }
public string salesforce { get; set; }
public string crm_last_sync { get; set; }
public string crm_url { get; set; }
public string is_do_not_email { get; set; }
public string is_do_not_call { get; set; }
public string opted_out { get; set; }
public string is_reviewed { get; set; }
public string is_starred { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
When the method reaches
return Ok(idstr);
The code resumes where the method was called and therefore never reaches
return Ok(update);

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

Categories

Resources