JsonReaderException creating bulk index for elasticsearch - json

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.

Related

Setting an ObservableCollection = to a json response

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; }
}

One to one relationship Mysql EF6

Hi there I've been banging my head now for two days and haven't been able to solve this one: I have this data structure:
[
{
"LocalObservationDateTime": "2019-12-12T19:50:00+02:00",
"EpochTime": 1576173000,
"WeatherText": "Thunderstorm",
"WeatherIcon": 15,
"HasPrecipitation": true,
"Reciprocation": "Rain",
"IsDayTime": false,
"Temperature": {
"Metric": {
"Value": 13.7,
"Unit": "C",
"UnitType": 17
},
"Imperial": {
"Value": 57,
"Unit": "F",
"UnitType": 18
}
}
}
]
I designed my data like this:
Table1:
Id,
LocalObservationDateTime,
EpochTime
WeatherText,
WeatherIcon,
HasPrecipitation,
PrecipitationType,
IsDayTime,
TemperatureId
Table2
TemperatureId,
ImperialId,
MetricId
Table3
Id,
Value,
Unit,
UnitType
I connected FKs tables 3 Id ImperialId and MetricId in Table 3 and TemperatureId in Table 2 to TemperatureId in table1
these are my models:
[Table("currentweather")]
public class CurrentWeather
{
[Key, Column("id")]
public int Id { get; set; }
[Column("locationid")]
public int LocationId { get; set; }
[Column("localobservationdatetime")]
public DateTime LocalObservationDateTime { get; set; }
[Column("epochtime")]
public long EpochTime { get; set; }
[Column("weathertext")]
public string WeatherText { get; set; }
[Column("weathericon")]
public int WeatherIcon { get; set; }
[Column("hasprecipitation")]
public bool HasPrecipitation { get; set; }
[Column("precipitationtype")]
public string PrecipitationType { get; set; }
[Column("isdaytime")]
public bool IsDayTime { get; set; }
[ForeignKey("Temperature")]
[Column("temperatureid")]
public int TemperatureId { get; set; }
[Column("mobilelink")]
public string MobileLink { get; set; }
[Column("link")]
public string Link { get; set; }
[NotMapped]
public Temperature Temperature { get; set; }
}
[Table("temperature")]
public class Temperature
{
[Key, Column("tepmeratureid")]
public int TemperatureId { get; set; }
[ForeignKey("Imperial")]
[Column("imperialid")]
public int ImperialId { get; set; }
[ForeignKey("Metric")]
[Column("metricid")]
public int MetricId { get; set; }
[NotMapped]
public CurrentWeather CurrentWeather { get; set; }
[NotMapped]
public TemperatureUnit Imperial { get; set; }
[NotMapped]
public TemperatureUnit Metric { get; set; }
}
public class TemperatureUnit
{
public double Value { get; set; }
public Unit Unit { get; set; }
public int UnitType { get; set; }
[NotMapped]
public Temperature Temperature { get; set; }
}
public enum Unit { C,F}
I am using Mysql and Net.core EF6
When adding data only table 1 gets the data but the other two don't HELP!!!
Your json object doesn't match your database tables, so you'll have to do some mapping of those properties.
Note: the below code leaves off several properties, but you should be able to follow this and add them in as needed.
First, you need to make your json string into an object. If passed in from a controller you can use model binding; otherwise you'll have to deserialize it. Here's an appropriate view model for that:
public class CurrentWeatherViewModel
{
public DateTime LocalObservartionTime { get; set; }
public int EpochTime { get; set; }
public string WeatherText { get; set; }
//additional props here
public TemperatureViewModel Temperature { get; set; }
}
public class TemperatureViewModel
{
public MetricViewModel Metric { get; set; }
public ImperialViewModel Imperial { get; set; }
}
public class MetricViewModel
{
public decimal Value { get; set; }
public string Unit { get; set; }
public int UnitType { get; set; }
}
public class ImperialViewModel
{
public decimal Value { get; set; }
public string Unit { get; set; }
public int UnitType { get; set; }
}
You can deserialize the json string into that object like this:
var jsonString = " {\"EpochTime\": 1576173000,\"WeatherText\": \"Thunderstorm\",\"WeatherIcon\": 15,\"HasPrecipitation\": true,\"Reciprocation\": \"Rain\",\"IsDayTime\": false,\"Temperature\": {\"Metric\": {\"Value\": 13.7,\"Unit\": \"C\",\"UnitType\": 17},\"Imperial\": {\"Value\": 57,\"Unit\": \"F\",\"UnitType\": 18}}}";
CurrentWeatherViewModel currentWeatherViewModel = Newtonsoft.Json.JsonConvert.DeserializeObject<CurrentWeatherViewModel>(jsonString);
Once it's deserialized into the viewmodel object, you can create your entities and save them to the db:
CurrentWeather currentWeather = new CurrentWeather
{
WeatherText = currentWeatherViewModel.WeatherText,
Temperature = new Temperature
{
Measurements = new Measurement[] {
new Measurement {
Unit = currentWeatherViewModel.Temperature.Metric.Unit,
UnitType = currentWeatherViewModel.Temperature.Metric.UnitType,
Value = currentWeatherViewModel.Temperature.Metric.Value,
},
new Measurement {
Unit = currentWeatherViewModel.Temperature.Imperial.Unit,
UnitType = currentWeatherViewModel.Temperature.Imperial.UnitType,
Value = currentWeatherViewModel.Temperature.Imperial.Value,
}
}
}
};
db.CurrentWeathers.Add(currentWeather);
db.SaveChanges();
Here's the entity classes:
public class CurrentWeather
{
public int Id { get; set; }
public DateTime? LocalObservartionTime { get; set; }
public int EpochTime { get; set; }
public string WeatherText { get; set; }
//additional props here
public virtual Temperature Temperature { get; set; }
}
public class Temperature
{
public int Id { get; set; }
//relationship
public int CurrentWeatherId { get; set; }
//relationship
public virtual ICollection<Measurement> Measurements { get; set; }
}
public class Measurement
{
public int Id { get; set; }
public decimal Value { get; set; }
public string Unit { get; set; }
public int UnitType { get; set; }
//relationship
public int TemperatureId { get; set; }
public virtual Temperature Temperature { get; set; }
}

Error deserializing DateTime JSON fields in .Net Core 3.0

I've got a WPF / .Net Core 3.0 app which is consuming a Web API.
It executes a GET on an API endpoint and then tries to deserialize the JSON.
However, it's giving an error when trying to deserialize the DateTime fields.
Here's the code:
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>;
}
The ClientGetDto model 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"
},
...
]
The error I'm getting is:
"There was an error deserializing the object of type
System.Collections.Generic.List`1[[PropWorxManager.DTOs.ClientGetDto,
PropWorxManager, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null]].
DateTime content '2007-08-01T00:00:00' does not
start with '\/Date(' and end with ')\/' as required for
JSON."} System.Runtime.Serialization.SerializationException
After some research I tried this:
var settings = new DataContractJsonSerializerSettings
{
DateTimeFormat = new System.Runtime.Serialization.DateTimeFormat("o")
};
var serializer = new DataContractJsonSerializer(typeof(List<ClientGetDto>), settings);
But that then gives this error:
"There was an error deserializing the object of type
System.Collections.Generic.List`1[[PropWorxManager.DTOs.ClientGetDto,
PropWorxManager, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null]].
String '2007-08-01T00:00:00' was not recognized
as a valid
DateTime."} System.Runtime.Serialization.SerializationException
Any suggestions would be welcome. Thank you.
P.S. The API is also written in .Net Core 3.0 if that helps...
This worked:
var settings = new DataContractJsonSerializerSettings
{
DateTimeFormat = new System.Runtime.Serialization.DateTimeFormat("o")
};
var serializer = new DataContractJsonSerializer(typeof(List<ClientGetDto>), settings);

Deserializing a JSON stream from an API in .Net Core 3.0 leaving all fields null

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

Deserialize a json file with json.net with int values on structure

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.