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

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.

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

JsonReaderException creating bulk index for elasticsearch

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.

Mvc4 model base om JSON

I am writing an mVC4 application and i would like to create a model to generate the following JSON file:
{
"area": {
"areaid": "1",
"venueid": "41",
"fnames": "12",
"s": [{"Id":1,"V":"0,1,2,2,1,1,1,0B-001,0,0,0,"},
{"Id":2,"V":"2,1,2,2,1,1,1,0B-001,0,0,0,"},
{"Id":3,"V":"3,1,2,2,1,1,1,0B-001,0,0,0,"}]
}
}
Something like that?
public class Area
{
[Key]
public int areaid { get; set; }
public int venueid { get; set; }
public int fnames { get; set; }
[ForeignKey("Id")]
public List<Book> s { get; set; }
}
public class Book
{
[Key]
public int Id { get; set; }
public string V { get; set; }
}
I think that should work. Here's the result from using Visual Studio 2013's Paste JSON as Classes feature...
public class Rootobject
{
public Area area { get; set; }
}
public class Area
{
public string areaid { get; set; }
public string venueid { get; set; }
public string fnames { get; set; }
public List<Book> s { get; set; }
}
public class Book
{
public int Id { get; set; }
public string V { get; set; }
}

Having trouble finding the right JSON request

I will appologise in advance if I am being really stupid here, but I cant find the right syntax to extract some data from a JSON return. The following is the returned JSON data:
{
"version":"1.0",
"encoding":"UTF-8",
"feed":{
"xmlns":"http://www.w3.org/2005/Atom",
"xmlns$openSearch":"http://a9.com/-/spec/opensearchrss/1.0/",
"xmlns$gsx":"http://schemas.google.com/spreadsheets/2006/extended",
"id":{
"$t":"https://spreadsheets.google.com/feeds/list/0AhySzEddwIC1dEN6bnNQYkRlVE50RlBRLUQ5YlZhNUE/1/public/basic"
},
"updated":{
"$t":"2012-12-03T10:33:13.778Z"
},
"category":[
{
"scheme":"http://schemas.google.com/spreadsheets/2006",
"term":"http://schemas.google.com/spreadsheets/2006#list"
}
],
"title":{
"type":"text",
"$t":"Sheet1"
},
"link":[
{
"rel":"alternate",
"type":"text/html",
"href":"https://spreadsheets.google.com/pub?key\u003d0AhySzEddwIC1dEN6bnNQYkRlVE50RlBRLUQ5YlZhNUE"
},
{
"rel":"http://schemas.google.com/g/2005#feed",
"type":"application/atom+xml",
"href":"https://spreadsheets.google.com/feeds/list/0AhySzEddwIC1dEN6bnNQYkRlVE50RlBRLUQ5YlZhNUE/1/public/basic"
},
{
"rel":"self",
"type":"application/atom+xml",
"href":"https://spreadsheets.google.com/feeds/list/0AhySzEddwIC1dEN6bnNQYkRlVE50RlBRLUQ5YlZhNUE/1/public/basic?alt\u003djson"
}
],
"author":[
{
"name":{
"$t":"rourkie"
},
"email":{
"$t":"rourkie#gmail.com"
}
}
],
"openSearch$totalResults":{
"$t":"1"
},
"openSearch$startIndex":{
"$t":"1"
},
"entry":[
{
"id":{
"$t":"https://spreadsheets.google.com/feeds/list/0AhySzEddwIC1dEN6bnNQYkRlVE50RlBRLUQ5YlZhNUE/1/public/basic/cn6ca"
},
"updated":{
"$t":"2012-12-03T10:33:13.778Z"
},
"category":[
{
"scheme":"http://schemas.google.com/spreadsheets/2006",
"term":"http://schemas.google.com/spreadsheets/2006#list"
}
],
"title":{
"type":"text",
"$t":"5872.64"
},
"content":{
"type":"text",
"$t":"change: 3.6"
},
"link":[
{
"rel":"self",
"type":"application/atom+xml",
"href":"https://spreadsheets.google.com/feeds/list/0AhySzEddwIC1dEN6bnNQYkRlVE50RlBRLUQ5YlZhNUE/1/public/basic/cn6ca"
}
]
}
]
}
}
I am trying to extract the "change" figure, with the following:
feed.entry[4].content.$t
but it just keeps returning an error.
Can anyone shed some light on what I am doing wrong??
Thanks
JSONLint - http://jsonlint.com/ - is pretty handy for this.
The JSON you posted only has one object in the entry array (unless you just posted it as an example)...so it would be:
feed.entry[0].content.$t
Using json2csharp.com (http://json2csharp.com/) You can paste in json and it will give you a class matching the json allowing you to easily parse it. Check How can I parse JSON with C#? on how to use JsonConvert. I believe you can find it in nuget packages. Keep in mind the class I have pasted below will not work directly, because of the naming of some of the fields in the json. You may have to rename them manually and map them.
public class Id
{
public string __invalid_name__$t { get; set; }
}
public class Updated
{
public string __invalid_name__$t { get; set; }
}
public class Category
{
public string scheme { get; set; }
public string term { get; set; }
}
public class Title
{
public string type { get; set; }
public string __invalid_name__$t { get; set; }
}
public class Link
{
public string rel { get; set; }
public string type { get; set; }
public string href { get; set; }
}
public class Name
{
public string __invalid_name__$t { get; set; }
}
public class Email
{
public string __invalid_name__$t { get; set; }
}
public class Author
{
public Name name { get; set; }
public Email email { get; set; }
}
public class OpenSearchTotalResults
{
public string __invalid_name__$t { get; set; }
}
public class OpenSearchStartIndex
{
public string __invalid_name__$t { get; set; }
}
public class Id2
{
public string __invalid_name__$t { get; set; }
}
public class Updated2
{
public string __invalid_name__$t { get; set; }
}
public class Category2
{
public string scheme { get; set; }
public string term { get; set; }
}
public class Title2
{
public string type { get; set; }
public string __invalid_name__$t { get; set; }
}
public class Content
{
public string type { get; set; }
public string __invalid_name__$t { get; set; }
}
public class Link2
{
public string rel { get; set; }
public string type { get; set; }
public string href { get; set; }
}
public class Entry
{
public Id2 id { get; set; }
public Updated2 updated { get; set; }
public List<Category2> category { get; set; }
public Title2 title { get; set; }
public Content content { get; set; }
public List<Link2> link { get; set; }
}
public class Feed
{
public string xmlns { get; set; }
public string __invalid_name__xmlns$openSearch { get; set; }
public string __invalid_name__xmlns$gsx { get; set; }
public Id id { get; set; }
public Updated updated { get; set; }
public List<Category> category { get; set; }
public Title title { get; set; }
public List<Link> link { get; set; }
public List<Author> author { get; set; }
public OpenSearchTotalResults __invalid_name__openSearch$totalResults { get; set; }
public OpenSearchStartIndex __invalid_name__openSearch$startIndex { get; set; }
public List<Entry> entry { get; set; }
}
public class RootObject
{
public string version { get; set; }
public string encoding { get; set; }
public Feed feed { get; set; }
}