wcf send json and receive json response with different object - json

I want to create a service which receives json object of one type and sends back different object. When im using same object type for request and response, everything is working. But when I change the object that im sending back I get bad request 400 can some one help?
public interface IOrderService
{
[OperationContract]
[WebInvoke(UriTemplate = "/GetTablesDataResponse",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json, Method = "POST")]
MetaDataResponseContract GetTablesDataResponse(TablesMetaDataContract TablesRequest);
}
}
TablesMetaDataContract
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
namespace GetMetaDataWcfSvc
{
[DataContract]
public class TablesMetaDataContract
{
[DataMember]
public Header Header { get; set; }
[DataMember]
public Body Body { get; set; }
}
[DataContract]
public class Header
{}
[DataContract]
public class Body
{
[DataMember]
public get_MetaData_request get_MetaData_request { get; set; }
}
[DataContract]
public class get_MetaData_request
{
[DataMember]
public service_control service_control { get; set; }
[DataMember]
public service_data service_data { get; set; }
}
[DataContract]
public class service_control
{
[DataMember]
public string application_src { get; set; }
[DataMember]
public string transaction_id { get; set; }
[DataMember]
public string process_name { get; set; }
[DataMember]
public string request_datetime { get; set; }
}
[DataContract]
public class service_data
{
[DataMember]
public tables_name tables_name { get; set; }
}
[DataContract]
public class tables_name
{
[DataMember]
public List<string> table_name { get; set; }
}
}
MetaDataResponseContract
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Runtime.Serialization;
using System.Web;
namespace GetMetaDataWcfSvc
{
[DataContract]
public class MetaDataResponseContract
{
[DataMember]
public service_status service_status { get; set;}
[DataMember]
public OutputParameters OutputParameters {get; set; }
}
[DataContract]
public class service_status
{
[DataMember]
public string return_code { get; set; }
[DataMember]
public string return_desc { get; set; }
}
[DataContract]
public class Column
{
[DataMember]
public string name { get; set; }
[DataMember]
public string sqltype { get; set; }
[DataMember]
public string text { get; set; }
}
[DataContract]
public class Row
{
[DataMember]
public List<Column> Column { get; set; }
}
[DataContract]
public class Table
{
[DataMember]
public string name { get; set; }
[DataMember]
public List<Row> Row { get; set; }
}
[DataContract]
public class OutputParameters
{
[DataMember]
public Table Table { get; set; }
}
}
Service function
public MetaDataResponseContract GetTablesDataResponse(TablesMetaDataContract TablesRequest)
{
TablesRequest.Body.get_MetaData_request.service_control.process_name = "server";
string ProcessName = TablesRequest.Body.get_MetaData_request.service_control.process_name;
string RequestDateTime = TablesRequest.Body.get_MetaData_request.service_control.request_datetime;
List<string> TablesList = new List<string> { };
GetDataTable(ProcessName);
MetaDataResponseContract TablesListResponse = new MetaDataResponseContract();
TablesListResponse.service_status.return_desc = "susccess";
//if i return TablesRequest and change return type in function it is working
return TablesListResponse;
}
client
DataContractJsonSerializer ser =
new DataContractJsonSerializer(typeof(TablesMetaDataContract));
MemoryStream mem = new MemoryStream();
ser.WriteObject(mem, TablesRequest);
string data =
Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);
WebClient webClient = new WebClient();
webClient.Headers["Content-type"] = "application/json";
webClient.Encoding = Encoding.UTF8;
try
{
string t = webClient.UploadString("http://localhost:63702/OrderService.svc/GetTablesDataResponse", "POST", data);
}
catch (Exception ex)
{
string x = ex.ToString();
}

Related

MVC model returns null

I have a json string in my controller. When i deserialize that into my model, it's returning a null value. The very strange part here is that this was working a while ago then stopped. Any thoughts as to what's wrong here? This is an api call, so i don't have the luxury of changing the json either. tCustLst is the problem child that is returning null from the model.
json (result):
"{\"response\":{\"cErrorMessage\":\"\",\"moreRecordsAvailable\":false,\"tCustLst\":{\"t-custLst\":[{\"custNo\":324161.0,\"shipTo\":\"\",\"name\":\"TEST \\/ (NICKNAME)\",\"addr1\":\"P.O. BOX 111\",\"addr2\":\"\",\"city\":\"NYC\",\"state\":\"NY\",\"zipCd\":\"55555-1234\",\"ordBal\":0.0,\"totalBal\":20451.67,\"sortFld\":\" 123456\"}]}}}"
controller code:
CustomerList.Rootobject records = JsonConvert.DeserializeObject<CustomerList.Rootobject>(result);
return View(records);
model:
using Newtonsoft.Json;
using System.Collections.Generic;
namespace WebappsIntranet.Models
{
public class CustomerList
{
public class Rootobject
{
public string cErrorMessage { get; set; }
public bool moreRecordsAvailable { get; set; }
public tCustLst tCustList { get; set; }
}
public class tCustLst
{
[JsonProperty("t-custLst")]
public List<tCustcomerList> tcustomerlist { get; set; }
}
public class tCustcomerList {
public float custNo { get; set; }
public string shipTo { get; set; }
public string name { get; set; }
public string addr1 { get; set; }
public string addr2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string zipCd { get; set; }
public float ordBal { get; set; }
public float totalBal { get; set; }
public string sortFld { get; set; }
}
}
}

Deserialize Json with varying dictionary size in unity

I am using newtonsoft.json in unity and trying to deserialize from an api endpoint.
I have my Json response set up kind of like this..
{}pattern_order
{}LB
{}LC
Actual end point:
{"key":"value","pattern_order":{"LB":{"A":[{"order":["A","G","X","D"],"style":"SK"},{"order":["D","X","D"],"style":"SK"}],"B":[{"order":["A","D","X","G","C"],"style":"SK"},{"order":["C","X","D"],"style":"SK"},{"order":["D","G","X"],"style":"AT"}]},"LC":{"A":[{"order":["A","D","X","G","C"],"style":"AT"},{"order":["C","X","D"],"style":"SK"}],"B":[{"order":["A","D","X","G","C"],"style":"AT"},{"order":["C","X","D"],"style":"SK"}]}}}
Here, LB and LC have a similar structure, but I want to add more objects inside pattern_order.
What is the best way to deserialize such a json in unity?
After removing the . that shouldn't be there as mentioned I just have put it into Json2csharp which results in
// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
public class A
{
public List<string> order { get; set; }
public string style { get; set; }
}
public class B
{
public List<string> order { get; set; }
public string style { get; set; }
}
public class LB
{
public List<A> A { get; set; }
public List<B> B { get; set; }
}
public class LC
{
public List<A> A { get; set; }
public List<B> B { get; set; }
}
public class PatternOrder
{
public LB LB { get; set; }
public LC LC { get; set; }
}
public class Root
{
public string key { get; set; }
public List<string> levels { get; set; }
public PatternOrder pattern_order { get; set; }
}
From there it is actually a simple step:
public class Thingy
{
public List<string> order;
public string style;
}
public class Root
{
public string key;
public List<string> levels;
// HERE YOU GO!
public Dictionary<string, Dictionary<string, Thingy[]>> pattern_order;
}
and
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
You can rename Thingy (and all other classes) to whatever you want ;)

Implementing deserialization with RestSharp and Newtonsoft.Json

I am rather new to c# but I am building something to help me at work. We have a REST API which I am trying to tap into but I am having issues when it comes to deserializing the response.
My code:
namespace BSRestCleint
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string key = "xxxxxxxx";
string endPoint = "https://api.broadsign.com:10889/rest";
private void bRun_Click(object sender, EventArgs e)
{
var client = new RestClient(endPoint);
var request = new RestRequest("/host/v14/by_id", Method.GET);
request.AddHeader("accept", "application/json");
request.AddHeader("Authorization", "Bearer " + key);
request.AddParameter("domain_id", "103947039");
request.AddParameter("ids", "195392183");
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
request.RequestFormat = DataFormat.Json;
var response = client.Execute<Host>(request);
var host = JsonConvert.DeserializeObject<Host>(response.Content);
oResponse.Text = host.Name;
}
}
}
And this is my class:
namespace BSRestCleint
{
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.Runtime.Serialization.Json;
using System.IO;
public partial class Host
{
[JsonProperty("config_profile_bag_id")]
public long ConfigProfileBagId { get; set; }
[JsonProperty("container_id")]
public long ContainerId { get; set; }
[JsonProperty("db_pickup_tm_utc")]
public string DbPickupTmUtc { get; set; }
[JsonProperty("discovery_status")]
public long DiscoveryStatus { get; set; }
[JsonProperty("display_unit_id")]
public long DisplayUnitId { get; set; }
[JsonProperty("domain_id")]
public long DomainId { get; set; }
[JsonProperty("geolocation")]
public string Geolocation { get; set; }
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("nscreens")]
public long Nscreens { get; set; }
[JsonProperty("public_key_fingerprint")]
public string PublicKeyFingerprint { get; set; }
[JsonProperty("remote_clear_db_tm_utc")]
public string RemoteClearDbTmUtc { get; set; }
[JsonProperty("remote_reboot_tm_utc")]
public string RemoteRebootTmUtc { get; set; }
[JsonProperty("volume")]
public long Volume { get; set; }
}
}
Finally the returning json:
{
"not_modified_since":"2018-06-05T22:22:18Z",
"host":[
{
"active":true,
"config_profile_bag_id":0,
"container_id":0,
"db_pickup_tm_utc":"2018-01-11T10:12:55",
"discovery_status":0,
"display_unit_id":0,
"domain_id":103947039,
"geolocation":"(0,0)",
"id":195392183,
"license_end_date":null,
"licensed":true,
"name":"Broadsign Services - Mathias - 16x64",
"nscreens":0,
"primary_mac_address":"00:0c:29:e0:e6:22",
"public_key_fingerprint":"REDACTED",
"remote_clear_db_tm_utc":"1970-01-01T00:00:00",
"remote_reboot_tm_utc":"2017-12-12T10:17:23",
"secondary_mac_address":"",
"volume":-1
}
]
}
I know that if I only process this part my code works:
{
"active":true,
"config_profile_bag_id":0,
"container_id":0,
"db_pickup_tm_utc":"2018-01-11T10:12:55",
"discovery_status":0,
"display_unit_id":0,
"domain_id":103947039,
"geolocation":"(0,0)",
"id":195392183,
"license_end_date":null,
"licensed":true,
"name":"Broadsign Services - Mathias - 16x64",
"nscreens":0,
"primary_mac_address":"00:0c:29:e0:e6:22",
"public_key_fingerprint":"REDACTED",
"remote_clear_db_tm_utc":"1970-01-01T00:00:00",
"remote_reboot_tm_utc":"2017-12-12T10:17:23",
"secondary_mac_address":"",
"volume":-1
}
I'd like to know how I could make my code work to handle the whole json so that I don't need to regex the returning value. Some of the responses would return multiple instances unlike there where there's only 1. It's probably a very simple solution but my grasp of the language is rather minute as I am new to it.
Any help would be appreciated.
Since, you are getting the host as array inside the another root object so you can define a new class as which is wrapping Host (array)
public class RootObject
{
public DateTime not_modified_since { get; set; }
public List<Host> Host { get; set; }
}
deserialization code need to be updated as
var root = JsonConvert.DeserializeObject<RootObject>(response.Content);
If you see, here deserializtion will happen for RootObject instead of Host.
Now, to get all hosts, use the below code:
var hosts = root.Host;
Or the first host from received hosts
var firstHost = root.Host.First();
You can extract it like this, without introducing new class:
var js = JObject.Parse(response.Content);
var hosts = JArray.Parse(obj["host"].ToString());
foreach (JObject host in hosts)
{
var h = JsonConvert.DeserializeObject<Host>(host)
//do what you need to do with host
}
You mentioned that there can be multiple hosts, so, you have to convert it to JArray, and loop through the array.
use this as your Host class instead (renamed to RootObject)
public partial class RootObject
{
[JsonProperty("not_modified_since")]
public DateTimeOffset NotModifiedSince { get; set; }
[JsonProperty("host")]
public List<Host> Host { get; set; }
}
public partial class Host
{
[JsonProperty("active")]
public bool Active { get; set; }
[JsonProperty("config_profile_bag_id")]
public long ConfigProfileBagId { get; set; }
[JsonProperty("container_id")]
public long ContainerId { get; set; }
[JsonProperty("db_pickup_tm_utc")]
public DateTimeOffset DbPickupTmUtc { get; set; }
[JsonProperty("discovery_status")]
public long DiscoveryStatus { get; set; }
[JsonProperty("display_unit_id")]
public long DisplayUnitId { get; set; }
[JsonProperty("domain_id")]
public long DomainId { get; set; }
[JsonProperty("geolocation")]
public string Geolocation { get; set; }
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("license_end_date")]
public object LicenseEndDate { get; set; }
[JsonProperty("licensed")]
public bool Licensed { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("nscreens")]
public long Nscreens { get; set; }
[JsonProperty("primary_mac_address")]
public string PrimaryMacAddress { get; set; }
[JsonProperty("public_key_fingerprint")]
public string PublicKeyFingerprint { get; set; }
[JsonProperty("remote_clear_db_tm_utc")]
public DateTimeOffset RemoteClearDbTmUtc { get; set; }
[JsonProperty("remote_reboot_tm_utc")]
public DateTimeOffset RemoteRebootTmUtc { get; set; }
[JsonProperty("secondary_mac_address")]
public string SecondaryMacAddress { get; set; }
[JsonProperty("volume")]
public long Volume { get; set; }
}
}
then deserialize
var rootObject = JsonConvert.DeserializeObject<RootObject>(response.Content);
var hosts = rootObject .Host;

Deserialize OneNote Notebooks API Response

I'm getting an empty object when I try to Deserialize a OneNote GetAllNotebooks query.
string[] tempCapture = null;
var url = new Uri("https://graph.microsoft.com/v1.0/me/onenote/notebooks");
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
if (IsAuthenticated)
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
}
var response = await client.GetAsync(url);
var result = await response.Content.ReadAsStringAsync();
tbResponse.Text = result.ToString();
DataContractJsonSerializer ser1 = new DataContractJsonSerializer(typeof(List<Value>));
MemoryStream stream1 = new MemoryStream(Encoding.UTF8.GetBytes(tbResponse.Text.ToString()));
var obj1 = (List<Value>)ser1.ReadObject(stream1);
I'm trying to get a list of notebooks, names, links to add to a database. And my table structure matches the class below.
Here is my OneNote API class
public class Value
{
public bool isDefault { get; set; }
public string userRole { get; set; }
public bool isShared { get; set; }
public string sectionsUrl { get; set; }
public string sectionGroupsUrl { get; set; }
public Links links { get; set; }
public string name { get; set; }
public string self { get; set; }
public string createdBy { get; set; }
public string lastModifiedBy { get; set; }
public string lastModifiedTime { get; set; }
public string id { get; set; }
public string createdTime { get; set; }
}
Here is my new code with the RootObject. I'm still getting an error. It is in the catch exception.
var test = await client.GetAsync(url);
string testStr = await test.Content.ReadAsStringAsync();
DataContractJsonSerializer serial = new DataContractJsonSerializer(typeof(RootObject));
MemoryStream testStream = new MemoryStream(Encoding.UTF8.GetBytes(testStr));
try
{
var objx = (List<RootObject>)serial.ReadObject(testStream);
}
catch(Exception ex)
{
ex.ToString();
//"There was an error deserializing the object of type OneNoteSOAP2.RootObject. End element 'createdBy' from namespace '' expected. Found element 'user' from namespace ''."
}
You can use http://json2csharp.com/. Basically, just copy the value of our JSON being returned, and use the classes generated by this website. Use RootObject to deserialize.
I ran this for you and obtained these classes:
public class OneNoteClientUrl
{
public string href { get; set; }
}
public class OneNoteWebUrl
{
public string href { get; set; }
}
public class Links
{
public OneNoteClientUrl oneNoteClientUrl { get; set; }
public OneNoteWebUrl oneNoteWebUrl { get; set; }
}
public class Value
{
public string id { get; set; }
public string self { get; set; }
public string createdTime { get; set; }
public string name { get; set; }
public string createdBy { get; set; }
public string lastModifiedBy { get; set; }
public string lastModifiedTime { get; set; }
public bool isDefault { get; set; }
public string userRole { get; set; }
public bool isShared { get; set; }
public string sectionsUrl { get; set; }
public string sectionGroupsUrl { get; set; }
public Links links { get; set; }
}
public class RootObject
{
public List<Value> value { get; set; }
}

Web API, C#, Json Objects, Views

I have some issues with displaying data as a Json object in this ASP.NET Web API project. It is my first try, I don't have Views, I am gonna use Postman for testing. Can you give me some diretions how to display the model as an Json Object?
//UserController
public class UsersController : ApiController
{
private LearnToLearnContext db = new LearnToLearnContext();
private BaseRepository<Users> _repository = null;
public UsersController()
{
this._repository = new BaseRepository<Users>();
}
// GET: api/Users
[ResponseType(typeof(Users))]
public IHttpActionResult GetUsers()
{
var user = _repository.GetAll();
var bindingModel = Mapper.Map<UsersBindingModels>(user);
return Ok(bindingModel);
}
}
//UserModel
public class Users
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Unique]
[Required]
public string Email { get; set; }
[Required]
public string Password { get; set; }
public bool IsTeacher { get; set; }
public virtual List<Courses> Courses { get; set; }
}
//UserBindingModel
public class UsersBindingModels
{
[Required]
public string name { get; set; }
[Unique]
[Required]
public string email { get; set; }
[Required]
public string password { get; set; }
public bool isTeacher { get; set; }
public virtual List<Courses> Courses { get; set; }
}