I have 3 different lists in "UrnikPrevozov" class, I want to populate them with data from JSON for each list, but I am not quite sure how to correctly do it. Any help would be greatly appreciated.
This is my json:
{
"UrnikAvtobus": [
{
"Linija": 34,
"Trajanje": "01:15:00",
"Voznik": "Rojko Mulic",
"Vstop": "Velenje",
"Izstop": "Maribor",
"CenaVozovnice": 2.90
}
],
"UrnikAvto": [
{
"Znamka": "MERCEDES",
"Registerska": "LJ 455-AA",
"Vinjeta": 0,
"Vstop": "Maribor",
"Izstop": "Velenje",
"CenaVozovnice": 5.40
}
],
"UrnikKombi": [
{
"Sedezi": 8,
"Odhod": "2022-12-12T09:15:00",
"Prihod": "2022-12-12T12:31:00",
"Vstop": "Maribor",
"Izstop": "Ljubljana",
"CenaVozovnice": 3.70
}
]
}
My UrnikPrevozov class where I want to bind the data to the lists:
public class UrnikPrevozov : Prevoz
{
public List<AvtobusniPrevoz> UrnikBus { get; set; }
public List<AvtoPrevoz> UrnikAvto { get; set; }
public List<KombiPrevoz> UrnikKombi { get; set; }
}
This is how I read my json:
public void LoadJson()
{
string data = File.ReadAllText("./Data/data.json");
var urniki = JsonConvert.DeserializeObject<UrnikPrevozov>(data);
}
AvtoPrevoz class
public class AvtoPrevoz : Prevoz
{
public string Znamka { get; set; }
public string Registerska { get; set; }
public Vinjeta Vinjeta { get; set; }
public AvtoPrevoz(string znamka, string registerska, Vinjeta vinjeta, string vstop, string izstop, double cenaVozovnice) : base(vstop, izstop, cenaVozovnice)
{
Znamka = znamka;
Registerska = registerska;
Vinjeta = vinjeta;
}
}
Prevoz class
public abstract class Prevoz
{
public string Vstop { get; set; }
public string Izstop { get; set; }
public double CenaVozovnice { get; set; }
protected Prevoz(string vstop, string izstop, double cenaVozovnice)
{
Vstop = vstop;
Izstop = izstop;
CenaVozovnice = cenaVozovnice;
}
}
Method call in main:
UrnikPrevozov urnik = new UrnikPrevozov();
urnik.LoadJson();
Your UrnikPrevozov class should not be inheriting Prevoz since it does not need the fields Prevoz has. And you would need parameterless constructors for all your classes.
Update: Full working code:
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Linq;
using System.IO;
public class Program
{
public static void Main()
{
string json = File.ReadAllText("./Data/data.json");
UrnikPrevozov urnik = JsonConvert.DeserializeObject<UrnikPrevozov>(json);
Console.WriteLine(urnik.UrnikAvto.First().Vstop);
}
}
public class AvtobusniPrevoz : Prevoz
{
public int Linija { get; set; }
public string Trajanje { get; set; }
public string Voznik { get; set; }
}
public class AvtoPrevoz : Prevoz
{
public string Znamka { get; set; }
public string Registerska { get; set; }
public int Vinjeta { get; set; }
}
public class KombiPrevoz : Prevoz
{
public int Sedezi { get; set; }
public DateTime Odhod { get; set; }
public DateTime Prihod { get; set; }
}
public abstract class Prevoz
{
public string Vstop { get; set; }
public string Izstop { get; set; }
public double CenaVozovnice { get; set; }
}
public class UrnikPrevozov
{
public List<AvtobusniPrevoz> UrnikBus { get; set; }
public List<AvtoPrevoz> UrnikAvto { get; set; }
public List<KombiPrevoz> UrnikKombi { get; set; }
}
you have a typo in UrnikPrevozov class , replace UrnikBus by UrnikAvtobus, also you don't need any base class here. After this everything will be working properly (tested in Visual Studio)
public class UrnikPrevozov
{
public List<AvtobusniPrevoz> UrnikAvtobus { get; set; }
public List<AvtoPrevoz> UrnikAvto { get; set; }
public List<KombiPrevoz> UrnikKombi { get; set; }
}
Related
I am using the SharePoint REST API to do a search. I am pulling back the JSON results and reading them as follows:
HttpWebRequest endpointRequest = (HttpWebRequest)HttpWebRequest.Create(querystring);
endpointRequest.Method = "GET";
endpointRequest.Accept = "application/json; odata=verbose";
endpointRequest.UseDefaultCredentials = true;
HttpWebResponse endpointResponse =(HttpWebResponse)endpointRequest.GetResponse();
Stream webStream = endpointResponse.GetResponseStream();
StreamReader responseReader = new StreamReader(webStream);
var results = responseReader.ReadToEnd();
This works fine, I can see the results in JSON format. So I created a class from the JSON in VS 2017 and here is the classes created from the JSON (this was done automatically with File=>Paste Special=>Paste JSON As Classes:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class SharePointRESTResults
{
public class Rootobject
{
public D d { get; set; }
}
public class D
{
public Query query { get; set; }
}
public class Query
{
public __Metadata __metadata { get; set; }
public int ElapsedTime { get; set; }
public Primaryqueryresult PrimaryQueryResult { get; set; }
public Properties1 Properties { get; set; }
public Secondaryqueryresults SecondaryQueryResults { get; set; }
public string SpellingSuggestion { get; set; }
public Triggeredrules TriggeredRules { get; set; }
}
public class __Metadata
{
public string type { get; set; }
}
public class Primaryqueryresult
{
public __Metadata1 __metadata { get; set; }
public Customresults CustomResults { get; set; }
public string QueryId { get; set; }
public string QueryRuleId { get; set; }
public object RefinementResults { get; set; }
public Relevantresults RelevantResults { get; set; }
public object SpecialTermResults { get; set; }
}
public class __Metadata1
{
public string type { get; set; }
}
public class Customresults
{
public __Metadata2 __metadata { get; set; }
public object[] results { get; set; }
}
public class __Metadata2
{
public string type { get; set; }
}
public class Relevantresults
{
public __Metadata3 __metadata { get; set; }
public object GroupTemplateId { get; set; }
public object ItemTemplateId { get; set; }
public Properties Properties { get; set; }
public object ResultTitle { get; set; }
public object ResultTitleUrl { get; set; }
public int RowCount { get; set; }
public Table Table { get; set; }
public int TotalRows { get; set; }
public int TotalRowsIncludingDuplicates { get; set; }
}
public class __Metadata3
{
public string type { get; set; }
}
public class Properties
{
public Result[] results { get; set; }
}
public class Result
{
public __Metadata4 __metadata { get; set; }
public string Key { get; set; }
public string Value { get; set; }
public string ValueType { get; set; }
}
public class __Metadata4
{
public string type { get; set; }
}
public class Table
{
public __Metadata5 __metadata { get; set; }
public Rows Rows { get; set; }
}
public class __Metadata5
{
public string type { get; set; }
}
public class Rows
{
public Result1[] results { get; set; }
}
public class Result1
{
public __Metadata6 __metadata { get; set; }
public Cells Cells { get; set; }
}
public class __Metadata6
{
public string type { get; set; }
}
public class Cells
{
public Result2[] results { get; set; }
}
public class Result2
{
public __Metadata7 __metadata { get; set; }
public string Key { get; set; }
public object Value { get; set; }
public string ValueType { get; set; }
}
public class __Metadata7
{
public string type { get; set; }
}
public class Properties1
{
public Result3[] results { get; set; }
}
public class Result3
{
public __Metadata8 __metadata { get; set; }
public string Key { get; set; }
public string Value { get; set; }
public string ValueType { get; set; }
}
public class __Metadata8
{
public string type { get; set; }
}
public class Secondaryqueryresults
{
public __Metadata9 __metadata { get; set; }
public object[] results { get; set; }
}
public class __Metadata9
{
public string type { get; set; }
}
public class Triggeredrules
{
public __Metadata10 __metadata { get; set; }
public object[] results { get; set; }
}
public class __Metadata10
{
public string type { get; set; }
}
}
}
So I now am trying to deserialize the results as follows:
SharePointRESTResults resultX = JsonConvert.DeserializeObject<SharePointRESTResults>(results());
The results I need should be in the Result2 Class. The problem I have is that this line is setting resultX = to "ConsoleApplication1.SharePointRESTResults" and nothing more. I looked in the JSON Serializing and Deserializing here: JSON Documentation but still cannot get the results into the class so I can pull out the data. I appreciate any help.
The main points are -
The Account Declaration.
JsonProperty attribute.
NOTE : If you have an object Which keys can change, Then you need to use a
Dictionary<string, T>
. A regular class won't work for that; neither will a
List<T>
.
I have a nested json string, instead of using arrays the next level is another json structure. This creates a mess of deserializing using traditional methods.
Most other answers dealing with parsing json have clearly defined structures, and in most cases can be solved using online tools such as http://json2csharp.com/. But because this JSON doesn't use arrays properly I'm having trouble coming up with a solution to deserialize it.
For example:
{
"time":1516824466,
"global":{
"workers":1,
"hashrate":0
},
"algos":{
"scrypt-n":{
"workers":1,
"hashrate":79752.92436043094,
"hashrateString":"79.75 KH"
}
},
"pools":{
"garlicoin":{
"name":"garlicoin",
"symbol":"GRLC",
"algorithm":"scrypt-n",
"poolStats":{
"validShares":"22855",
"validBlocks":"3",
"invalidShares":"59",
"invalidRate":"0.0026",
"totalPaid":"296.42722209999999999"
},
"blocks":{
"pending":0,
"confirmed":2,
"orphaned":1
},
"workers":{
"Gf3ZXqhWKkm8qLhSHvyrawiCiooYeU9eQu":{
"shares":365.07991498000007,
"invalidshares":0,
"hashrate":79752.92436043094,
"hashrateString":"79.75 KH"
},
"Gz2Llan6hTkm8qLhSHh34awiCiooYe17heT":{
"shares":365.07991498000007,
"invalidshares":0,
"hashrate":79752.92436043094,
"hashrateString":"79.75 KH"
}
},
"hashrate":79752.92436043094,
"workerCount":1,
"hashrateString":"79.75 KH"
}
}
}
I'm having trouble deserializing these two parts specifically:
"algos":{
"scrypt-n":{
"workers":1,
"hashrate":79752.92436043094,
"hashrateString":"79.75 KH"
}
},
"workers":{
"Gf3ZXqhWKkm8qLhSHvyrawiCiooYeU9eQu":{
"shares":365.07991498000007,
"invalidshares":0,
"hashrate":79752.92436043094,
"hashrateString":"79.75 KH"
},
"Gz2Llan6hTkm8qLhSHh34awiCiooYe17heT":{
"shares":365.07991498000007,
"invalidshares":0,
"hashrate":79752.92436043094,
"hashrateString":"79.75 KH"
}
},
The Code I've Tried
namespace pooldecode
{
public static class Serialize
{
public static string ToJson(this jsonDecode.Root self)
{
return JsonConvert.SerializeObject(self, Converter.Settings);
}
}
public class Converter
{
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
};
}
public class jsonDecode
{
public static Root FromJson(string json) => JsonConvert.DeserializeObject<Root>(json/*, Converter.Settings*/);
public partial class Root
{
[J("time")] public long Time { get; set; }
[J("global")] public Global Global { get; set; }
[J("algos")] public List<Algos> Algos { get; set; }
[J("pools")] public List<Pools> Pools { get; set; }
}
public partial class Algos
{
[J("workers")] public int Workers { get; set; }
[J("hashrate")] public double Hashrate { get; set; }
[J("hashrateString")] public string HashrateString { get; set; }
}
public partial class Global
{
[J("workers")] public int Workers { get; set; }
[J("hashrate")] public long Hashrate { get; set; }
}
public partial class Pools
{
[J("crypto")] public List<Crypto> Crypto { get; set; }
}
public partial class Crypto
{
[J("name")] public string Name { get; set; }
[J("symbol")] public string Symbol { get; set; }
[J("algorithm")] public string Algorithm { get; set; }
[J("poolStats")] public PoolStats PoolStats { get; set; }
[J("blocks")] public Blocks Blocks { get; set; }
[J("workers")] public Workers Workers { get; set; }
[J("hashrate")] public double Hashrate { get; set; }
[J("workerCount")] public long WorkerCount { get; set; }
[J("hashrateString")] public string HashrateString { get; set; }
}
public partial class Blocks
{
[J("pending")] public long Pending { get; set; }
[J("confirmed")] public long Confirmed { get; set; }
[J("orphaned")] public long Orphaned { get; set; }
}
public partial class PoolStats
{
[J("validShares")] public string ValidShares { get; set; }
[J("validBlocks")] public string ValidBlocks { get; set; }
[J("invalidShares")] public string InvalidShares { get; set; }
[J("invalidRate")] public string InvalidRate { get; set; }
[J("totalPaid")] public string TotalPaid { get; set; }
}
public partial class Workers
{
[J("worker")] public List<Workers> Worker { get; set; }
[J("shares")] public double Shares { get; set; }
[J("invalidshares")] public long Invalidshares { get; set; }
[J("hashrate")] public double Hashrate { get; set; }
[J("hashrateString")] public string HashrateString { get; set; }
}
public partial class Worker
{
[J("shares")] public double Shares { get; set; }
[J("invalidshares")] public long Invalidshares { get; set; }
[J("hashrate")] public double Hashrate { get; set; }
[J("hashrateString")] public string HashrateString { get; set; }
}
}
}
Algos, Pools and Workers have named properties as childrens, you can't deserialize them as List<T> since they are Dictionary<string, T>,
Use these classes to deserialize:
public partial class Root
{
[JsonPropertyAttribute("time")] public long Time { get; set; }
[JsonPropertyAttribute("global")] public Global Global { get; set; }
[JsonPropertyAttribute("algos")] public Dictionary<string, Algo> Algos { get; set; }
[JsonPropertyAttribute("pools")] public Dictionary<string, Pool> Pools { get; set; }
}
public partial class Global
{
[JsonPropertyAttribute("workers")] public int Workers { get; set; }
[JsonPropertyAttribute("hashrate")] public long Hashrate { get; set; }
}
public partial class Algo
{
[JsonPropertyAttribute("workers")] public int Workers { get; set; }
[JsonPropertyAttribute("hashrate")] public double Hashrate { get; set; }
[JsonPropertyAttribute("hashrateString")] public string HashrateString { get; set; }
}
public partial class Pool
{
[JsonPropertyAttribute("name")] public string Name { get; set; }
[JsonPropertyAttribute("symbol")] public string Symbol { get; set; }
[JsonPropertyAttribute("algorithm")] public string Algorithm { get; set; }
[JsonPropertyAttribute("poolStats")] public PoolStats PoolStats { get; set; }
[JsonPropertyAttribute("blocks")] public Blocks Blocks { get; set; }
[JsonPropertyAttribute("workers")] public Dictionary<string, Worker> Workers { get; set; }
[JsonPropertyAttribute("hashrate")] public double Hashrate { get; set; }
[JsonPropertyAttribute("workerCount")] public long WorkerCount { get; set; }
[JsonPropertyAttribute("hashrateString")] public string HashrateString { get; set; }
}
public partial class Blocks
{
[JsonPropertyAttribute("pending")] public long Pending { get; set; }
[JsonPropertyAttribute("confirmed")] public long Confirmed { get; set; }
[JsonPropertyAttribute("orphaned")] public long Orphaned { get; set; }
}
public partial class PoolStats
{
[JsonPropertyAttribute("validShares")] public string ValidShares { get; set; }
[JsonPropertyAttribute("validBlocks")] public string ValidBlocks { get; set; }
[JsonPropertyAttribute("invalidShares")] public string InvalidShares { get; set; }
[JsonPropertyAttribute("invalidRate")] public string InvalidRate { get; set; }
[JsonPropertyAttribute("totalPaid")] public string TotalPaid { get; set; }
}
public partial class Worker
{
[JsonPropertyAttribute("shares")] public double Shares { get; set; }
[JsonPropertyAttribute("invalidshares")] public long Invalidshares { get; set; }
[JsonPropertyAttribute("hashrate")] public double Hashrate { get; set; }
[JsonPropertyAttribute("hashrateString")] public string HashrateString { get; set; }
}
{
"StudentInformation": {
"rollNumber": null,
"isClassLeader": false,
"result": "Pass"
},
"CollegeInformation": {
"allClass": ["A", "B"],
"currencyAccepted": "INR",
"calendarDates": [],
"currencyCode": "INR",
"collegeCode": null,
"hasBulidingFundPrices": false,
"hasHostel": false,
"hasSecurityFares": false
},
"Collegetrips": [{
"tripsdate": [{
"departureTripDate": "2017-08-15 00:00:00",
"Places": [{
"destination": "Bombay",
"price": [{
"priceAmount": 1726
}]
}]
}]
}]
}
In the above json file i need to retrieve only "priceAmount": 1726. Please anyone suggest how can able to achieve?
You can use System.Web.Script.Serialization (you need to add a reference to System.Web.Extensions):
dynamic json = new JavaScriptSerializer()
.DeserializeObject(jsonString);
decimal price = json["Collegetrips"][0]
["tripsdate"][0]
["Places"][0]
["price"][0]
["priceAmount"]; // 1726
Note that you can pretty much traverse the json in this manner using indexes and key names.
Hi try this,
public void Main()
{
string sJSON = "{\"StudentInformation\": {\"rollNumber\": null,\"isClassLeader\": false,\"result\": \"Pass\"},\"CollegeInformation\": {\"allClass\": [\"A\", \"B\"],\"currencyAccepted\": \"INR\",\"calendarDates\": [],\"currencyCode\": \"INR\",\"collegeCode\": null,\"hasBulidingFundPrices\": false,\"hasHostel\": false,\"hasSecurityFares\": false},\"Collegetrips\": [{\"tripsdate\": [{\"departureTripDate\": \"2017-08-15 00:00:00\",\"Places\": [{\"destination\": \"Bombay\",\"price\": [{\"priceAmount\": 1726}]}]}]}]}";
Rootobject obj = Newtonsoft.Json.JsonConvert.DeserializeObject<Rootobject>(sJSON);
Price price = obj.Collegetrips.Select(ct =>
{
var r = ct.tripsdate.Select(td =>
{
var r1 = td.Places.Select(p =>
{
Price itemPrice = p.price.FirstOrDefault();
return itemPrice;
}).FirstOrDefault();
return r1;
}).FirstOrDefault();
return r;
}).FirstOrDefault();
if (price != null)
Console.Write(price.priceAmount);
else
Console.Write("Not Found!");
}
public class Rootobject
{
public Studentinformation StudentInformation { get; set; }
public Collegeinformation CollegeInformation { get; set; }
public Collegetrip[] Collegetrips { get; set; }
}
public class Studentinformation
{
public object rollNumber { get; set; }
public bool isClassLeader { get; set; }
public string result { get; set; }
}
public class Collegeinformation
{
public string[] allClass { get; set; }
public string currencyAccepted { get; set; }
public object[] calendarDates { get; set; }
public string currencyCode { get; set; }
public object collegeCode { get; set; }
public bool hasBulidingFundPrices { get; set; }
public bool hasHostel { get; set; }
public bool hasSecurityFares { get; set; }
}
public class Collegetrip
{
public Tripsdate[] tripsdate { get; set; }
}
public class Tripsdate
{
public string departureTripDate { get; set; }
public Place[] Places { get; set; }
}
public class Place
{
public string destination { get; set; }
public Price[] price { get; set; }
}
public class Price
{
public int priceAmount { get; set; }
}
I use:
http://json2csharp.com/
to get a class representing the Json Object.
public class StudentInformation
{
public object rollNumber { get; set; }
public bool isClassLeader { get; set; }
public string result { get; set; }
}
public class CollegeInformation
{
public List<string> allClass { get; set; }
public string currencyAccepted { get; set; }
public List<object> calendarDates { get; set; }
public string currencyCode { get; set; }
public object collegeCode { get; set; }
public bool hasBulidingFundPrices { get; set; }
public bool hasHostel { get; set; }
public bool hasSecurityFares { get; set; }
}
public class Price
{
public int priceAmount { get; set; }
}
public class Place
{
public string destination { get; set; }
public List<Price> price { get; set; }
}
public class Tripsdate
{
public string departureTripDate { get; set; }
public List<Place> Places { get; set; }
}
public class Collegetrip
{
public List<Tripsdate> tripsdate { get; set; }
}
public class JsonResponse
{
public StudentInformation StudentInformation { get; set; }
public CollegeInformation CollegeInformation { get; set; }
public List<Collegetrip> Collegetrips { get; set; }
}
After that I use Newtonsoft.Json to fill the Class:
using Newtonsoft.Json;
namespace GitRepositoryCreator.Common
{
class JObjects
{
public static string Get(object p_object)
{
return JsonConvert.SerializeObject(p_object);
}
internal static T Get<T>(string p_object)
{
return JsonConvert.DeserializeObject<T>(p_object);
}
}
}
You can call it like that:
JsonResponse jsonClass = JObjects.Get<JsonResponse>(stringJson);
string stringJson = JObjects.Get(jsonClass);
PS:
If your json variable name is no valid C# name you can fix that like this:
public class Exception
{
[JsonProperty(PropertyName = "$id")]
public string id { get; set; }
public object innerException { get; set; }
public string message { get; set; }
public string typeName { get; set; }
public string typeKey { get; set; }
public int errorCode { get; set; }
public int eventId { get; set; }
}
I'm using the Petfinder API and trying to return a root object in my C# code. I used the Json class generator to generate the classes, but the Deserialize function is returning nulls.
This is my C# code:
using (var client = new WebClient())
{
var json = new WebClient().DownloadString("http://api.petfinder.com/shelter.getPets?format=json&key=<key>&id=<id>");
Petfinder deserializedPet = JsonConvert.DeserializeObject<Petfinder>(json);
}
The Petfinder object is defined as:
internal class Petfinder
{
[JsonProperty("#xmlns:xsi")]
public string XmlnsXsi { get; set; }
[JsonProperty("lastOffset")]
public LastOffset LastOffset { get; set; }
[JsonProperty("pets")]
public Pets Pets { get; set; }
[JsonProperty("header")]
public Header Header { get; set; }
[JsonProperty("#xsi:noNamespaceSchemaLocation")]
public string XsiNoNamespaceSchemaLocation { get; set; }
}
The first few lines of the json string is as follows:
{"#encoding":"iso-8859-1","#version":"1.0","petfinder":{"#xmlns:xsi":"http://www.w3.org/2001/XMLSchema-instance","lastOffset":{"$t":"25"},"pets":{"pet":[{"options":{"option":[{"$t":"hasShots"},{"$t":"altered"},{"$t":"housetrained"}]},"breeds":{"breed":{"$t":"Domestic Medium Hair"}},"shelterPetId":{},"status":{"$t":"A"},"name":{"$t":"Jasmine"},...
If that helps at all.
I'm a newbie to json.net. What am I doing wrong?
Your class is wrong, take a look at the output from json2csharp.com for the example json you provided. Obviously the __invalid_name_$t needs to be manually fixed and the mapped using [JsonProperty].
public class LastOffset
{
public string __invalid_name__$t { get; set; }
}
public class Option
{
public string __invalid_name__$t { get; set; }
}
public class Options
{
public List<Option> option { get; set; }
}
public class Breed
{
public string __invalid_name__$t { get; set; }
}
public class Breeds
{
public Breed breed { get; set; }
}
public class ShelterPetId
{
}
public class Status
{
public string __invalid_name__$t { get; set; }
}
public class Name
{
public string __invalid_name__$t { get; set; }
}
public class Pet
{
public Options options { get; set; }
public Breeds breeds { get; set; }
public ShelterPetId shelterPetId { get; set; }
public Status status { get; set; }
public Name name { get; set; }
}
public class Pets
{
public List<Pet> pet { get; set; }
}
public class Petfinder
{
public string __invalid_name__#xmlns:xsi { get; set; }
public LastOffset lastOffset { get; set; }
public Pets pets { get; set; }
}
public class RootObject
{
public string __invalid_name__#encoding { get; set; }
public string __invalid_name__#version { get; set; }
public Petfinder petfinder { get; set; }
}
I am trying to generate C# class using the JSON string from here http://json2csharp.com/ this works fine. But I can't parse the JSON to the object generated by the website.
Here is the JSON string
{
"searchParameters":{
"key":"**********",
"system":"urn:oid:.8"
},
"message":" found one Person matching your search criteria.",
"_links":{
"self":{
"href":"https://integration.rest.api.test.com/v1/person?key=123456&system=12.4.34.."
}
},
"_embedded":{
"person":[
{
"details":{
"address":[
{
"line":["5554519 testdr"],
"city":"testland",
"state":"TT",
"zip":"12345",
"period":{
"start":"2003-10-22T00:00:00Z",
"end":"9999-12-31T23:59:59Z"
}
}
],
"name":[
{
"use":"usual",
"family":["BC"],
"given":["TWO"],
"period":{
"start":"9999-10-22T00:00:00Z",
"end":"9999-12-31T23:59:59Z"
}
}
],
"gender":{
"code":"M",
"display":"Male"
},
"birthDate":"9999-02-03T00:00:00Z",
"identifier":[
{
"use":"unspecified",
"system":"urn:oid:2.19.8",
"key":"",
"period":{
"start":"9999-10-22T00:00:00Z",
"end":"9999-12-31T23:59:59Z"
}
}
],
"telecom":[
{
"system":"email",
"value":"test#test.com",
"use":"unspecified",
"period":{
"start":"9999-10-22T00:00:00Z",
"end":"9999-12-31T23:59:59Z"
}
}
],
"photo":[
{
"content":{
"contentType":"image/jpeg",
"language":"",
"data":"",
"size":0,
"hash":"",
"title":"My Picture"
}
}
]
},
"enrolled":true,
"enrollmentSummary":{
"dateEnrolled":"9999-02-07T21:39:11.174Z",
"enroller":"test Support"
},
"_links":{
"self":{
"href":"https://integration.rest.api.test.com/v1/person/-182d-4296-90cc"
},
"unenroll":{
"href":"https://integration.rest.api.test.com/v1/person/1b018dc4-182d-4296-90cc-/unenroll"
},
"personLink":{
"href":"https://integration.rest.api.test.com/v1/person/-182d-4296-90cc-953c/personLink"
},
"personMatch":{
"href":"https://integration.rest.api.commonwellalliance.org/v1/person/-182d-4296-90cc-/personMatch?orgId="
}
}
}
]
}
}
Here is the code I use to convert to the object.
JavaScriptSerializer js = new JavaScriptSerializer();
var xx = (PersonsearchVM)js.Deserialize(jsonstr, typeof(PersonsearchVM));
Is there any other wat to generate the object and parse?
I think you have some invalid characters in your JSON string. Run it through a validator and add the necessary escape characters.
http://jsonlint.com/
You aren't casting it to the right object. Cast it to the type RootObject.
Eg
JavaScriptSerializer js = new JavaScriptSerializer();
var xx = (RootObject)js.Deserialize(jsonstr, typeof(RootObject));
The code that json 2 csharp creates is this:
public class SearchParameters
{
public string key { get; set; }
public string system { get; set; }
}
public class Self
{
public string href { get; set; }
}
public class LinKs
{
public Self self { get; set; }
}
public class Period
{
public string start { get; set; }
public string end { get; set; }
}
public class Address
{
public List<string> line { get; set; }
public string city { get; set; }
public string __invalid_name__state { get; set; }
public string zip { get; set; }
public Period period { get; set; }
}
public class PerioD2
{
public string start { get; set; }
public string end { get; set; }
}
public class Name
{
public string use { get; set; }
public List<string> family { get; set; }
public List<string> given { get; set; }
public PerioD2 __invalid_name__perio
d { get; set; }
}
public class Gender
{
public string __invalid_name__co
de { get; set; }
public string display { get; set; }
}
public class Period3
{
public string start { get; set; }
public string __invalid_name__end { get; set; }
}
public class Identifier
{
public string use
{ get; set; }
public string system { get; set; }
public string key { get; set; }
public Period3 period { get; set; }
}
public class Period4
{
public string start { get; set; }
public string end { get; set; }
}
public class Telecom
{
public string system { get; set; }
public string value { get; set; }
public string use { get; set; }
public Period4 period { get; set; }
}
public class Content
{
public string contentType { get; set; }
public string language { get; set; }
public string __invalid_name__dat
a { get; set; }
public int size { get; set; }
public string hash { get; set; }
public string title { get; set; }
}
public class Photo
{
public Content content { get; set; }
}
public class Details
{
public List<Address> address { get; set; }
public List<Name> name { get; set; }
public Gender gender { get; set; }
public string birthDate { get; set; }
public List<Identifier> identifier { get; set; }
public List<Telecom> telecom { get; set; }
public List<Photo> photo { get; set; }
}
public class EnrollmentSummary
{
public string dateEnrolled { get; set; }
public string __invalid_name__en
roller { get; set; }
}
public class Self2
{
public string href { get; set; }
}
public class UnEnroll
{
public string href { get; set; }
}
public class PersonLink
{
public string href { get; set; }
}
public class PersonMatch
{
public string href { get; set; }
}
public class Links2
{
public Self2 self { get; set; }
public UnEnroll __invalid_name__un
enroll { get; set; }
public PersonLink personLink { get; set; }
public PersonMatch personMatch { get; set; }
}
public class Person
{
public Details details { get; set; }
public bool __invalid_name__e
nrolled { get; set; }
public EnrollmentSummary enrollmentSummary { get; set; }
public Links2 _links { get; set; }
}
public class Embedded
{
public List<Person> person { get; set; }
}
public class RootObject
{
public SearchParameters searchParameters { get; set; }
public string message { get; set; }
public LinKs __invalid_name___lin
ks { get; set; }
public Embedded _embedded { get; set; }
}
The following function will convert JSON into a C# class where T is the class type.
public static T Deserialise<T>(string json)
{
T obj = Activator.CreateInstance<T>();
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
obj = (T)serializer.ReadObject(ms); //
return obj;
}
}
You need a reference to the System.Runtime.Serialization.json namespace.
The function is called in the following manner;
calendarList = Deserialise<GoogleCalendarList>(calendarListString);
calendarlist being the C# class and calendarListString the string containing the JSON.