Deserialize Json Object with for each - c#

var serverData = serverConnection.connect("login.php", pairs);
RootObject json = JsonConvert.DeserializeObject<RootObject>(await serverData);
foreach (Logined m in json.logined)
{
}
public class Logined
{
public string id { get; set; }
public string firsname { get; set; }
public string lastname { get; set; }
public string email { get; set; }
public string phone { get; set; }
public string profilePic { get; set; }
public string thumbnail { get; set; }
}
public class RootObject
{
public Logined logined { get; set; }
}
the error in the for each it says cannot operate on variables of type public definition for getenumerator

Your root object contains only a single Logined, so there is nothing to enumerate.
public class RootObject
{
public Logined logined { get; set; } //not a collection
}
foreach (Logined m in json.logined) //json.logined is a single object (not a collection)
{
}
If your server is returning a collection of Logined, you have to change your RootObject definition.
public class RootObject
{
public Logined[] logined { get; set; } //array of Logined
}

Related

JSON DeserializeObject to Model without Key Name

I currently have JSON coming in as follows:
{"36879":[{"min_qty":1,"discount_type":"%","csp_price":10}],"57950":[{"min_qty":1,"discount_type":"flat","csp_price":650}]}
This contains a list of the following records
ProductId
MinQty
DiscountType
Price
I need to deserialize this into the following model:
public class CustomerSpecificPricing
{
string productId { get; set; }
public virtual List<CustomerSpecificPricingDetail> CustomerSpecificPricingDetails { get; set; }
}
public class CustomerSpecificPricingDetail
{
public string min_qty { get; set; }
public string discount_type { get; set; }
public string csp_price { get; set; }
}
The problem is that the "productId" of each record is missing the key name.
If I run my JSON through J2C, I get the following:
public class 36879 {
public int min_qty { get; set; }
public string discount_type { get; set; }
public int csp_price { get; set; }
}
public class 57950 {
public int min_qty { get; set; }
public string discount_type { get; set; }
public int csp_price { get; set; }
}
public class Root {
public List<_36879> _36879 { get; set; }
public List<_57950> _57950 { get; set; }
}
Which is obviously incorrect.
How would I deserialize my object correctly?
You would need to deserialize it into a dictionary first and then map it into the format you require after. Something like this should work:
var dict = JsonConvert.DeserializeObject<Dictionary<string, IEnumerable<CustomerSpecificPricingDetail>>>();
var result = dict.Select(kvp => new CustomerSpecificPricing { ProductId = Int32.Parse(kvp.Key), CustomerSpecificPricingDetails = kvp.Value });
Id also recommend you follow the conventional standards of naming. In this case properties in classes should be PascalCase,
e.g. your classes now become:
public class CustomerSpecificPricing
{
[JsonProperty("productId ")]
public string ProductId { get; set; }
public virtual List<CustomerSpecificPricingDetail> CustomerSpecificPricingDetails { get; set; }
}
and
public class CustomerSpecificPricingDetail
{
[JsonProperty("min_qty")]
public string MinQty { get; set; }
[JsonProperty("discount_type ")]
public string DiscountType { get; set; }
[JsonProperty("csp_price ")]
public string CspPrice { get; set; }
}

Parse json string to a class populating it's subclasses

I have this string returned to my code behind:
string json = "[[{'nome':'joe','cpf':'54'},{'id':'8','nome':'Legendagem','valor':'5'}],[{'nome':'jane','cpf':'22'},{'id':'1','nome':'Legendagem2','valor':'6'}]]";
and I have 3 classes:
public class ItemCart
{
public UserCart user { get; set; }
public CursoCart curso { get; set; }
}
public class UserCart
{
public string nome { get; set; }
public string email { get; set; }
public string cpf { get; set; }
}
public class CursoCart
{
public string id { get; set; }
public string desc { get; set; }
public string valor { get; set; }
}
what i want is to have the class UserCart/CursoCart class populated so I can loop inside itemCart and get the values, length etc of the UserCart/CursoCart items
eg:
UserCart user1 = itemCart[0].user;
supposing that I can't change the string, I'm trying this to convert, but now working:
List<ItemCart> itemCart = JsonConvert.DeserializeObject<List<ItemCart>>(json);
thank you for any help.
As I see from your json it is an array.
The following ItemCart and Deserialization may work for you.
public class Program
{
public static void Main()
{
string json = "[[{'nome':'joe','cpf':'54'},{'id':'8','nome':'Legendagem','valor':'5'}],[{'nome':'jane','cpf':'22'},{'id':'1','nome':'Legendagem2','valor':'6'}]]";
var ItemCartList = JsonConvert.DeserializeObject<List<Item[]>>(json);
}
}
public class ItemCart
{
public Item[][] ItemList { get; set; }
}
public class Item
{
public string nome { get; set; }
public string cpf { get; set; }
public string id { get; set; }
public string valor { get; set; }
}

Deserializing Server returned String to JSON

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

Json.Net Deserialize Returning Nulls

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

Generate C# object from Json string and parse Json string to generated object

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.

Categories