I am currently writing a Xamarin forms application. The issue I am facing is that I am receiving a Json Response from my API, and storing it in a var JsonReponse. The code is as follows;
string UserId = Settings.CallUserId;
var client = new RestClient("http://blablablaAPiCall" + UserId);
client.Timeout = -1;
var request = new RestRequest(Method.GET);
request.AddHeader("Content-Type", "application/json");
var body = #"";
request.AddParameter("application/json", body, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
var JsonResponse = JsonConvert.DeserializeObject<Flights[]>(response.Content);
FlightsCollection = new ObservableCollection<Flights>
{
new Flights() {Id="1", SectorStart="1", Registration="A123",
Departure="Jhb", OffBlockTime="1242", Arrival="EC", OnBlockTime="1342",
TotalFlightTime="0100", InstrumentTime="00" }
};
The class I made looks like this;
public class Flights
{
public string Id { get; set; }
public string UserId { get; set; }
public string EntryDate { get; set; }
public string IsMasterId { get; set; }
public string SectorStart { get; set; }
public string SectorEnd { get; set; }
public string AircraftType { get; set; }
public string Registration { get; set; }
public string PicName { get; set; }
public string PilotFunction { get; set; }
public string Departure { get; set; }
public string Arrival { get; set; }
public string OffBlockTime { get; set; }
public string OnBlockTime { get; set; }
public string TotalFlightTime { get; set; }
public string NightLanding { get; set; }
public string Instructor { get; set; }
public string Simulator { get; set; }
public string NightTime { get; set; }
public string DayTime { get; set; }
public string InstrumentTime { get; set; }
public string ApproachType { get; set; }
public string NavAid { get; set; }
public string Place { get; set; }
public string FinalRemarks { get; set; }
}
At the top I declared an Obvservable Collection,
public ObservableCollection<Flights> FlightsCollection { get; set; }
So now the end goal would be for me to set my json response = Observable collection, as you can see I have done it statically, but now how do I do it with my json response?
My json response looks like this if needed,
[
{
"ID": 15,
"UserID": 10,
"EntryDate": "2022/01/02 2:34:20 PM",
"IsMasterID": true,
"SectorStart": 1,
"SectorEnd": 1,
"Aircraft_Type": "Unclassified",
"Registration": "aircraft reg",
"PICName": "Jordan Watts",
"PilotFunction": "PIC",
"Departure": "Jhb",
"Arrival": "EC",
"OffBlockTime": "00:00",
"OnBlockTime": "01:15",
"TotalFlightTime": "01:15",
"NightLanding": true,
"Instructor": true,
"Simulator": true,
"NightTime": "01:15",
"DayTime": "00:00",
"InstrumentTime": "0000",
"ApproachType": "VOR",
"NavAid": "nav",
"Place": "here",
"FinalRemarks": "this flight was cool"
},
{
"ID": 16,
"UserID": 10,
"EntryDate": "2022/01/02 2:44:10 PM",
"IsMasterID": true,
"SectorStart": 1,
"SectorEnd": 3,
"Aircraft_Type": "Unclassified",
"Registration": "aircraft reg",
"PICName": "Jordan Watts ",
"PilotFunction": "PICUS",
"Departure": "JHb",
"Arrival": "EC",
"OffBlockTime": "00:00",
"OnBlockTime": "01:00",
"TotalFlightTime": "01:00",
"NightLanding": true,
"Instructor": true,
"Simulator": true,
"NightTime": "01:00",
"DayTime": "00:00",
"InstrumentTime": "0000",
"ApproachType": "VOR",
"NavAid": "nav aid",
"Place": "here",
"FinalRemarks": "rhrbdidbf"
},
{
"ID": 18,
"UserID": 10,
"EntryDate": "2022/01/02 2:53:56 PM",
"IsMasterID": true,
"SectorStart": 1,
"SectorEnd": 2,
"Aircraft_Type": "Unclassified",
"Registration": "reg",
"PICName": "Jordan Watts ",
"PilotFunction": "PICUS",
"Departure": "Jhb",
"Arrival": "EC",
"OffBlockTime": "00:00",
"OnBlockTime": "02:15",
"TotalFlightTime": "02:15",
"NightLanding": true,
"Instructor": true,
"Simulator": true,
"NightTime": "02:15",
"DayTime": "00:0",
"InstrumentTime": "0000",
"ApproachType": "VOR",
"NavAid": "here",
"Place": "here 2",
"FinalRemarks": "flight 1 of 2 "
}
]
ObservableCollection accepts an IEnumerable which DeserializeObject can generate. Try this:
FlightsCollection = new ObservableCollection<Flights>(JsonConvert.DeserializeObject<List<Flights>>(response.Content))
if you want to have only some properties , you can create subclass accoring to your needs
FlightBase[] flights = JsonConvert.DeserializeObject<FlightBase[]>(response.Content);
ObservableCollection<FlightBase> FlightsCollection = new ObservableCollection<FlightBase>(flights);
classes
public class FlightBase
{
public int ID { get; set; }
public int SectorStart { get; set; }
public string Registration { get; set; }
public string Departure { get; set; }
public string Arrival { get; set; }
public string OffBlockTime { get; set; }
public string OnBlockTime { get; set; }
public string TotalFlightTime { get; set; }
public string InstrumentTime { get; set; }
}
public class Flight:FlightBase
{
public int UserID { get; set; }
public string EntryDate { get; set; }
public bool IsMasterID { get; set; }
public int SectorEnd { get; set; }
public string Aircraft_Type { get; set; }
public string PICName { get; set; }
public string PilotFunction { get; set; }
public bool NightLanding { get; set; }
public bool Instructor { get; set; }
public bool Simulator { get; set; }
public string NightTime { get; set; }
public string DayTime { get; set; }
public string ApproachType { get; set; }
public string NavAid { get; set; }
public string Place { get; set; }
public string FinalRemarks { get; set; }
}
Related
I've got a simple WPF / .Net Core 3.0 app which executes a GET on a Web API endpoint:
private HttpClient httpClient = new HttpClient();
private async Task GetClients()
{
var serializer = new DataContractJsonSerializer(typeof(List<ClientGetDto>));
var streamTask = httpClient.GetStreamAsync("https://mywebapp.com/api/Clients");
List<ClientGetDto> clientDtos = serializer.ReadObject(await streamTask) as List<ClientGetDto>;
}
ClientGetDto looks like this:
{
public int Id { get; set; }
public string ClientCode { get; set; }
public string ApiUrl { get; set; }
public string CompanyName { get; set; }
public string FranchiseName { get; set; }
public int? ProLicenses { get; set; }
public int? LiteLicenses { get; set; }
public int? ProSalesLicenses { get; set; }
public int? LiteSalesLicenses { get; set; }
public bool? IsActive { get; set; }
public DateTime? StartOfAgreementDate { get; set; }
public int? DebitOrderDay { get; set; }
public DateTime? DebitOrderStartDate { get; set; }
public decimal? ContractAmount { get; set; }
public bool? DebitOrderFormReceived { get; set; }
public bool? CancellationReceived { get; set; }
public DateTime? CancellationDate { get; set; }
public string CompanyRegNo { get; set; }
public string DbUrl { get; set; }
public string DbName { get; set; }
public double? CloudStorageQuota { get; set; }
public string Comments { get; set; }
public int? FranchiseId { get; set; }
public bool? IsTestDb { get; set; }
public bool? IsGumtreeRegistered { get; set; }
public int? FusionClientId { get; set; }
public string CountryCode { get; set; }
}
and the JSON that is returned by the API is:
[
{
"id": 3,
"clientCode": "cx0007",
"apiUrl": "https://mywebapp/api",
"companyName": "ACME Company",
"franchiseName": "ACME Franchise",
"proLicenses": 1,
"liteLicenses": 0,
"proSalesLicenses": 0,
"liteSalesLicenses": 0,
"isActive": true,
"startOfAgreementDate": "2007-08-01T00:00:00",
"debitOrderDay": 1,
"debitOrderStartDate": "2012-03-01T00:00:00",
"contractAmount": 695.00,
"debitOrderFormReceived": true,
"cancellationReceived": false,
"cancellationDate": "2012-10-18T00:00:00",
"companyRegNo": "",
"dbUrl": "mydb.co.za",
"dbName": "db1",
"cloudStorageQuota": 5.0,
"comments": null,
"franchiseId": null,
"isTestDb": false,
"isGumtreeRegistered": false,
"fusionClientId": null,
"countryCode": "US"
},
...
]
My problem is that the code is correctly deserializing the JSON into a List of ClientGetDto objects, but all the fields are null. It's not throwing any exceptions or anything. I've tried decorating my ClientGetDto model with [DataContract] and [DataMember] but it's made no difference (nor would it, since the names of the fields of the model are exactly the same as those in the JSON data)
Any ideas?
You should mark each property with [JsonPropertyName("")] because json is case sensitive (I think).
I have been having a hard time trying to figure this out that I've just about torn out all my hair now.
Using this section of code (Added a var result that I looking at with a stoppoint):
public async Task<string> GetHttpSPContentWithToken(string url, string token)
{
var httpClient = new System.Net.Http.HttpClient();
System.Net.Http.HttpResponseMessage response;
try
{
var request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, url);
//Add the token in Authorization header
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
response = await httpClient.SendAsync(request);
var content = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<SharePointListItems.Fields>(content);
return content;
}
catch (Exception ex)
{
return ex.ToString();
}
}
The content that I receive is this (updated getting rid of extra information):
{
"#odata.context": "https://graph.microsoft.com/v1.0/$metadata#sites('root')/lists('FBA0AB63-8453-4BB9-AA17-142A5D72A50D')/items/$entity",
"#odata.etag": "\"60d40002-0f08-4f29-afa7-0287137b863b,1\"",
"createdDateTime": "2018-08-07T14:28:47Z",
"eTag": "\"60d40002-0f08-4f29-afa7-0287137b863b,1\"",
"id": "1",
"lastModifiedDateTime": "2018-08-07T14:28:47Z",
"webUrl": "https://XXXX.sharepoint.com/Lists/TestList/1_.000",
"createdBy": {
"user": {
"email": "XXXX#XXXX.onmicrosoft.com",
"id": "b5f81cc6-f8b7-46b7-8e10-6ce1b9689c23",
"displayName": "TK"
}
},
"lastModifiedBy": {
"user": {
"email": "XXXX#XXXX.onmicrosoft.com",
"id": "b5f81cc6-f8b7-46b7-8e10-6ce1b9689c23",
"displayName": "TK"
}
},
"parentReference": {},
"contentType": {
"id": "0x010001403BD420356E4ABE3B63E5AEC0713D"
},
"fields#odata.context": "https://graph.microsoft.com/v1.0/$metadata#sites('root')/lists('FBA0AB63-8453-4BB9-AA17-142A5D72A50D')/items('1')/fields/$entity",
"fields": {
"#odata.etag": "\"60d40002-0f08-4f29-afa7-0287137b863b,1\"",
"Title": "1",
"UserName": "TK",
"UserAge": "47",
"UserTitle": "Developer"
}
}
I just want the values forUserAge, UserName, and UserTitle to put each into a textbox, but not sure how to pull them out.
I am pretty sure that I need to set up a class of some sort, but it is the #odata parts that are breaking my back.
Everything that I have tried just gives me back a null value. I see the value there, just not sure how to parse/pull it out.
I have looked at this (updated):
using Newtonsoft.Json;
using System;
public class SharePointListItems
{
public class UserCreated
{
public string email { get; set; }
public string id { get; set; }
public string displayName { get; set; }
}
public class CreatedBy
{
public UserCreated user { get; set; }
}
public class UserModified
{
public string email { get; set; }
public string id { get; set; }
public string displayName { get; set; }
}
public class LastModifiedBy
{
public UserModified user { get; set; }
}
public class ParentReference
{
}
public class ContentType
{
public string id { get; set; }
}
public class Fields
{
[JsonProperty("#odata.etag")]
public string ODataETag { get; set; }
public string Title { get; set; }
public string UserName { get; set; }
public string UserAge { get; set; }
public string UserTitle { get; set; }
}
public class RootObject
{
[JsonProperty("#odata.context")]
public string ODataContext { get; set; }
[JsonProperty("#odata.etag")]
public string ODataETag { get; set; }
public DateTime createdDateTime { get; set; }
public string eTag { get; set; }
public string id { get; set; }
public DateTime lastModifiedDateTime { get; set; }
public string webUrl { get; set; }
public CreatedBy createdBy { get; set; }
public LastModifiedBy lastModifiedBy { get; set; }
public ParentReference parentReference { get; set; }
public ContentType contentType { get; set; }
[JsonProperty("fields#odata.context")]
public string FieldsODataContext { get; set; }
public Fields fields { get; set; }
}
}
But then I run into the issue that there is two [JsonProperty("#odata.etag")].
The [JsonProperty] custom attribute is added to the C# property that actually holds that value. Instead of putting the attribute on the Title or createDateTime property, you need to put them on their own properties:
public class RootObject
{
[JsonProperty("#odata.context")]
public string ODataContext { get; set; }
[JsonProperty("#odata.etag")]
public string ODataETag { get; set; }
// No attribute needed here
public DateTime createdDateTime { get; set; }
// etc...
Also, you are trying to parse the content as a Fields class, but it is a RootObject; you need to use
JsonConvert.DeserializeObject<SharePointListItems.RootObject>(content)
To get the object.
Can someone help me to deserialize this JSON file?
{
"result": "success",
"records": {
"504498959": {
"nif": 504498959,
"seo_url": "triworld-equipamentos-informaticos-e-de-telecomunicacoes-unipessoal-lda",
"title": "Triworld - Equipamentos Inform\u00e1ticos e de Telecomunica\u00e7\u00f5es, Unipessoal Lda",
"address": "Rua Doutor Francisco Noronha, N 31",
"pc4": "4700",
"pc3": "355",
"city": "Braga",
"activity": "O com\u00e9rcio, importa\u00e7\u00f5es, exporta\u00e7\u00f5es e representa\u00e7\u00f5es de material e equipamento inform\u00e1tico, de telecomunica\u00e7\u00f5es; montagem, instala\u00e7\u00e3o, assist\u00eancia t\u00e9cnica, desenvolvimento de programas inform\u00e1ticos e outros similares.",
"status": "active",
"cae": "47781",
"contacts": {
"email": null,
"phone": "253261844",
"website": null,
"fax": "253613646"
},
"structure": {
"nature": "UNI",
"capital": "0.00",
"capital_currency": "EUR"
},
"geo": {
"region": "Braga",
"county": "Braga",
"parish": "S\u00e3o Vicente"
},
"place": {
"address": "Rua Doutor Francisco Noronha, N 31",
"pc4": "4700",
"pc3": "355",
"city": "Braga"
},
"racius": "http:\/\/www.racius.com\/triworld-equipamentos-informaticos-e-de-telecomunicacoes-unipessoal-lda\/",
"alias": "Triworld - Equip. Informaticos e de Telecomunica\u00e7\u00f5es,unipes., Lda",
"portugalio": "http:\/\/www.portugalio.com\/triworld-equip-informaticos-e-de-telecomunicacoes-unipes\/"
}
},
"nif_validation": true,
"is_nif": true,
"credits": {
"used": "Triworld - Equipamentos Informáticos e de Telecomunicações, Unipessoal Lda",
"left": {
"month": 993,
"day": 99,
"hour": 9,
"minute": 0,
"paid": 0
}
}
}
I'm using this code
using Newtonsoft.Json;
public class Rootobject
{
public string result { get; set; }
public Records records { get; set; }
public bool nif_validation { get; set; }
public bool is_nif { get; set; }
public Credits credits { get; set; }
}
public class Records
{
public _504498959 _504498959 { get; set; }
}
public class _504498959
{
public int nif { get; set; }
public string seo_url { get; set; }
public string title { get; set; }
public string address { get; set; }
public string pc4 { get; set; }
public string pc3 { get; set; }
public string city { get; set; }
public string activity { get; set; }
public string status { get; set; }
public string cae { get; set; }
public Contacts contacts { get; set; }
public Structure structure { get; set; }
public Geo geo { get; set; }
public Place place { get; set; }
public string racius { get; set; }
public string alias { get; set; }
public string portugalio { get; set; }
}
public class Contacts
{
public object email { get; set; }
public string phone { get; set; }
public object website { get; set; }
public string fax { get; set; }
}
public class Structure
{
public string nature { get; set; }
public string capital { get; set; }
public string capital_currency { get; set; }
}
public class Geo
{
public string region { get; set; }
public string county { get; set; }
public string parish { get; set; }
}
public class Place
{
public string address { get; set; }
public string pc4 { get; set; }
public string pc3 { get; set; }
public string city { get; set; }
}
public class Credits
{
public string used { get; set; }
public Left left { get; set; }
}
public class Left
{
public int month { get; set; }
public int day { get; set; }
public int hour { get; set; }
public int minute { get; set; }
public int paid { get; set; }
}
protected void VerificaNif(object sender, EventArgs e)
{
Rootobject jsonfileroot = JsonConvert.DeserializeObject<Rootobject>(get_web_content("http://www.triworld.pt/4FPIL83K.json"));
// need to use "records": { "504498959": { "title": "Triworld - Equipamentos Inform\u00e1ticos e de Telecomunica\u00e7\u00f5es, Unipessoal Lda", on a textbox named Nome.Text
if (jsonfileroot.result == "success")
{
Nome.Text = jsonfileroot.records._504498959.title;
}
else
{
erro.Text = " Nif is Invalid";
}
}
but it gives me an NullReferenceException, it can not reach the title.
Could someone help me please? thanks.
Here's a working .NetFiddle. It should auto-run. Otherwise just click RUN on that page. See the console output below on that page.
https://dotnetfiddle.net/rMA3Nt
Answer Details:
Change the declaration of your classes as shown below. Once you do that, the following code de-serializes correctly. Here's the output from my console app.
Console App output
Console App Code
class Program
{
static void Main(string[] args)
{
string theJson = "{ \"result\": \"success\", \"records\": { \"504498959\": { \"nif\": 504498959, \"seo_url\": \"triworld-equipamentos-informaticos-e-de-telecomunicacoes-unipessoal-lda\", \"title\": \"Triworld - Equipamentos Inform\u00e1ticos e de Telecomunica\u00e7\u00f5es, Unipessoal Lda\", \"address\": \"Rua Doutor Francisco Noronha, N 31\", \"pc4\": \"4700\", \"pc3\": \"355\", \"city\": \"Braga\", \"activity\": \"O com\u00e9rcio, importa\u00e7\u00f5es, exporta\u00e7\u00f5es e representa\u00e7\u00f5es de material e equipamento inform\u00e1tico, de telecomunica\u00e7\u00f5es; montagem, instala\u00e7\u00e3o, assist\u00eancia t\u00e9cnica, desenvolvimento de programas inform\u00e1ticos e outros similares.\", \"status\": \"active\", \"cae\": \"47781\", \"contacts\": { \"email\": null, \"phone\": \"253261844\", \"website\": null, \"fax\": \"253613646\" }, \"structure\": { \"nature\": \"UNI\", \"capital\": \"0.00\", \"capital_currency\": \"EUR\" }, \"geo\": { \"region\": \"Braga\", \"county\": \"Braga\", \"parish\": \"S\u00e3o Vicente\" }, \"place\": { \"address\": \"Rua Doutor Francisco Noronha, N 31\", \"pc4\": \"4700\", \"pc3\": \"355\", \"city\": \"Braga\" }, \"racius\": \"http://www.racius.com/triworld-equipamentos-informaticos-e-de-telecomunicacoes-unipessoal-lda/\", \"alias\": \"Triworld - Equip. Informaticos e de Telecomunica\u00e7\u00f5es,unipes., Lda\", \"portugalio\": \"http://www.portugalio.com/triworld-equip-informaticos-e-de-telecomunicacoes-unipes/\" } }, \"nif_validation\": true, \"is_nif\": true, \"credits\": { \"used\": \"Triworld - Equipamentos Informáticos e de Telecomunicações, Unipessoal Lda\", \"left\": { \"month\": 993, \"day\": 99, \"hour\": 9, \"minute\": 0, \"paid\": 0 } } }";
Rootobject theRecords = JsonConvert.DeserializeObject<Rootobject>(theJson);
if (theRecords != null)
{
Console.WriteLine("Deserialization succeeded :)");
if (theRecords.result == "success")
{
Console.WriteLine(" # of Records: {0}", theRecords.records.Count);
int recordCount = 1;
foreach (var record in theRecords.records)
{
Console.WriteLine(" Record #{0}", recordCount);
Console.WriteLine(" Key: {0}", record.Key);
Console.WriteLine(" nif: {0}", record.Value.nif);
Console.WriteLine(" seo_url: {0}", record.Value.seo_url);
Console.WriteLine(" title: {0}", record.Value.title);
Console.WriteLine(" address: {0}", record.Value.address);
Console.WriteLine(" city: {0}", record.Value.city);
Console.WriteLine(" alias: {0}", record.Value.alias);
Console.WriteLine(" portugalio : {0}", record.Value.portugalio);
recordCount++;
}
}
}
else
{
Console.WriteLine("Deserialization failed :(");
}
Console.ReadLine();
}
}
Here is how you need to modify your class declaration.
Console App Classes
public class Rootobject
{
public string result { get; set; }
public Dictionary<int, Location> records { get; set; }
public bool nif_validation { get; set; }
public bool is_nif { get; set; }
public Credits credits { get; set; }
}
public class Location
{
public int nif { get; set; }
public string seo_url { get; set; }
public string title { get; set; }
public string address { get; set; }
public string pc4 { get; set; }
public string pc3 { get; set; }
public string city { get; set; }
public string activity { get; set; }
public string status { get; set; }
public string cae { get; set; }
public Contacts contacts { get; set; }
public Structure structure { get; set; }
public Geo geo { get; set; }
public Place place { get; set; }
public string racius { get; set; }
public string alias { get; set; }
public string portugalio { get; set; }
}
public class Contacts
{
public object email { get; set; }
public string phone { get; set; }
public object website { get; set; }
public string fax { get; set; }
}
public class Structure
{
public string nature { get; set; }
public string capital { get; set; }
public string capital_currency { get; set; }
}
public class Geo
{
public string region { get; set; }
public string county { get; set; }
public string parish { get; set; }
}
public class Place
{
public string address { get; set; }
public string pc4 { get; set; }
public string pc3 { get; set; }
public string city { get; set; }
}
public class Credits
{
public string used { get; set; }
public Left left { get; set; }
}
public class Left
{
public int month { get; set; }
public int day { get; set; }
public int hour { get; set; }
public int minute { get; set; }
public int paid { get; set; }
}
Key Things To Note:
The RootObject has a Dictionary<int, Location> records that will have the int value as key and the object contained inside as a Location object.
If the int values could be duplicate in your final json, then change it to a List<NameValuePair<string,Location>>
The numeric key for the records entity will be the key of the Dictionary object inside the RootObject. The value will be the class called Location (I gave it that name, maybe something is more appropriate. You would know best.
I created a WCF Rest Service. I try to Post method usage. I send request from client, request getting from service method. But request object (CompanyDTO) fields values are null. Where is problem? I could' nt find.
Service post method
public void SaveCompany(CompanyDTO NewCompany)
{
try
{
CompanyManager manager = new CompanyManager();
manager.Save(NewCompany);
WebOperationContext ctx = WebOperationContext.Current;
ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;
}
catch (Exception ex)
{
throw new FaultException(new FaultReason(ex.Message));
}
}
Contract service interface
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "SaveCompany")]
void SaveCompany(CompanyDTO NewCompany);
CompantDTO class
public class CompanyDTO
{
public string IDENTIFIER { get; set; }
public string TYPE { get; set; }
public string USER_TYPE { get; set; }
public string FIRST_NAME { get; set; }
public string MIDDLE_NAME { get; set; }
public string FAMILY_NAME { get; set; }
public string COMPANY_NAME { get; set; }
public Nullable<int> COMPANY_NO { get; set; }
public string LEGAL_OFFICE { get; set; }
public Nullable<System.DateTime> FOUNDATION_DATE { get; set; }
public string BOARDOFTRADE_NAME { get; set; }
public string BOARDOFTRADE_ID { get; set; }
public string MERSIS_NO { get; set; }
public string TAPDK_NO { get; set; }
public string TRADE_REGISTRATION_NO { get; set; }
public string TRADE_REGISTRATION_OFFICE { get; set; }
public string TAX_IDENTIFICATION_NO { get; set; }
public Nullable<System.DateTime> DIGITAL_SIGN_VALIDITY_DATE { get; set; }
public string TAX_OFFICE { get; set; }
public string TAX_OFFICE_CODE { get; set; }
public Nullable<short> STATUS { get; set; }
public Nullable<int> SYS_VERSION { get; set; }
public Nullable<System.DateTime> SYS_LAST_UPDATE { get; set; }
}
Client request body
{
"CompanyDTO":
{
"IDENTIFIER":"34501599398",
"TYPE":"1",
"USER_TYPE":"1",
"FIRST_NAME":"Ebru",
"MIDDLE_NAME":"sws",
"FAMILY_NAME":"sd",
"COMPANY_NAME":"NULL",
"COMPANY_NO": "123",
"LEGAL_OFFICE": "DSF",
"FOUNDATION_DATE":"2015-03-02",
"BOARDOFTRADE_NAME":"SAD",
"BOARDOFTRADE_ID":"ASD",
"MERSIS_NO":"DASD",
"TAPDK_NO":"NULASDASDL",
"TRADE_REGISTRATION_NO":"NULL",
"TRADE_REGISTRATION_OFFICE":"ADS",
"TAX_IDENTIFICATION_NO":"NUASDSALL",
"DIGITAL_SIGN_VALIDITY_DATE": "2015-03-02",
"TAX_OFFICE":"ASDAD",
"TAX_OFFICE_CODE":"ASDA",
"STATUS": "1",
"SYS_VERSION" : "1",
"SYS_LAST_UPDATE": "2015-03-02"
}
}
It seems you need to get rid of "CompanyDTO" in your json, so it looks likes this:
{
"IDENTIFIER":"34501599398",
"TYPE":"1",
"USER_TYPE":"1",
"FIRST_NAME":"Ebru",
"MIDDLE_NAME":"sws",
"FAMILY_NAME":"sd",
"COMPANY_NAME":"NULL",
"COMPANY_NO": "123",
"LEGAL_OFFICE": "DSF",
"FOUNDATION_DATE":"2015-03-02",
"BOARDOFTRADE_NAME":"SAD",
"BOARDOFTRADE_ID":"ASD",
"MERSIS_NO":"DASD",
"TAPDK_NO":"NULASDASDL",
"TRADE_REGISTRATION_NO":"NULL",
"TRADE_REGISTRATION_OFFICE":"ADS",
"TAX_IDENTIFICATION_NO":"NUASDSALL",
"DIGITAL_SIGN_VALIDITY_DATE": "2015-03-02",
"TAX_OFFICE":"ASDAD",
"TAX_OFFICE_CODE":"ASDA",
"STATUS": "1",
"SYS_VERSION" : "1",
"SYS_LAST_UPDATE": "2015-03-02"
}
This is my first attempt using elasticsearch. I'm not sure how to troubleshoot the JsonReaderException error below.
var result = client.Bulk(d => descriptor);
results in an exception error
An exception of type 'Newtonsoft.Json.JsonReaderException' occurred in
Newtonsoft.Json.dll but was not handled in user code
Additional information: Error reading string. Unexpected token:
StartObject. Path 'items[0].index.error', line 1, position 108.
var client = new ElasticClient();
client.DeleteIndex("Tracks");
client.CreateIndex("Tracks", c => c
.NumberOfReplicas(1)
.NumberOfShards(6)
.AddMapping<vw_MusicTracks>(m => m.MapFromAttributes()));
var descriptor = new BulkDescriptor();
var context = new MerchEntities();
var sqlTracks = context.vw_MusicTracks.ToList<vw_MusicTracks>();
foreach (var order in sqlTracks)
{
descriptor.Index<vw_MusicTracks>(op => op.Index("Tracks").Document(order).Type("Track").Id(order.IMUTrackId));
}
var result = client.Bulk(d => descriptor);
Console.WriteLine("job's done");
Console.ReadKey();
vw_MusicRules.cs
using Nest;
using System.ComponentModel.DataAnnotations;
using System;
using System.Collections.Generic;
namespace MusicStore
{
[ElasticType(Name = "Track", IdProperty = "IMUTrackId")]
public partial class vw_MusicTracks
{
[Key]
public int IMUTrackId { get; set; }
public int IMUTrackTypeId { get; set; }
public int AreaId { get; set; }
public int GenreId { get; set; }
public int CityId { get; set; }
public int ArtistId { get; set; }
public System.DateTime Live { get; set; }
public Nullable<System.DateTime> LiveThrough { get; set; }
public decimal Value { get; set; }
public short Priority { get; set; }
public System.DateTime LastModified { get; set; }
public int LastModifierId { get; set; }
public System.DateTime Created { get; set; }
public string IMUTrackType { get; set; }
public string ModifierUserName { get; set; }
public string ModifierFirstName { get; set; }
public string ModifierLastName { get; set; }
public string ModifierEmail { get; set; }
public string AreaName { get; set; }
public Nullable<int> Department { get; set; }
public Nullable<int> Class { get; set; }
public Nullable<int> SubClass { get; set; }
public string Class { get; set; }
public string GenreName { get; set; }
public string ArtistName { get; set; }
public string CityName { get; set; }
}
}
Serialized sqlTracks
[
{
"IMUTrackId": 3,
"IMUTrackTypeId": 1,
"AreaId": 1,
"GenreId": -1,
"CityId": -1,
"ArtistId": -1,
"Live": "2014-01-01T00:00:00",
"LiveThrough": "2015-11-11T00:00:00",
"Value": 1.2195,
"Priority": 1,
"LastModified": "2014-02-25T00:00:00",
"LastModifierId": 218,
"Created": "2014-02-25T00:00:00",
"IMUTrackType": "Mult",
"ModifierUserName": "SystemUser",
"ModifierFirstName": "First",
"ModifierLastName": "",
"ModifierEmail": "dev#email.ex",
"AreaName": "Pl",
"Department": 1,
"Class": 1a,
"SubClass": 0,
"GenreName": "",
"ArtistName": "",
"CityName": ""
}
]
changing the index to all lower case solved the issue.