Deserialize Json List to C# List objects - c#

I have class which return json string but I want to deserilize it into C# List Objects. My current code look like this
public class JsonBuilder
{
public static string BuildJson(DateTime fromDate, DateTime toDate)
{
var list = new List<dynamic>();
// create list with json object from service
var jsonObjList = JsonConvert.SerializeObject(list);
var des = (List<JsonObject>)JsonConvert.DeserializeObject(jsonObjList, typeof(List<JsonObject>));
return JsonConvert.SerializeObject(list);
}
Exception thrown when it tries to deserialize the "serialized" json string
An exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll but was not handled in user code
Additional information: Error converting value
InnerException:
{"Could not cast or convert from System.String to MvcWebApp.Models.JsonObject."}

Have you tried this:
var des = (List<DeserializeObjects>)JsonConvert.DeserializeObject(jsonObjList, jsonObjList.GetType()));
or this:
var des = (List<DeserializeObjects>)JsonConvert.DeserializeObject(jsonObjList, typeof(List<dynamic>));
else this post could also help you to achieve your goal:
Deserialize json object into dynamic object using Json.net

try this
var jsonObjList = JsonConvert.SerializeObject(list);
dynamic resultList = JsonConvert.DeserializeObject(jsonObjList);

I would try with this class
public class Author
{
public int id { get; set; }
public string slug { get; set; }
public string name { get; set; }
public string first_name { get; set; }
public string last_name { get; set; }
public string nickname { get; set; }
public string url { get; set; }
public string description { get; set; }
}
public class CustomFields
{
public List<string> tags { get; set; }
}
public class Post
{
public int id { get; set; }
public string type { get; set; }
public string slug { get; set; }
public string url { get; set; }
public string status { get; set; }
public string title { get; set; }
public string title_plain { get; set; }
public string content { get; set; }
public string excerpt { get; set; }
public string date { get; set; }
public string modified { get; set; }
public List<object> categories { get; set; }
public List<object> tags { get; set; }
public Author author { get; set; }
public List<object> comments { get; set; }
public List<object> attachments { get; set; }
public int comment_count { get; set; }
public string comment_status { get; set; }
public CustomFields custom_fields { get; set; }
}
public class YourObject
{
public string status { get; set; }
public int count { get; set; }
public int count_total { get; set; }
public int pages { get; set; }
public List<Post> posts { get; set; }
}
Then, you deserialize with this :
var yourObject = JsonConvert.DeserializeObject<YourObject>(json);

Related

Why my deserialization is giving me an error Newtonsoft.Json.JsonConvert?

public List<CoinMarket> GetCoinMarket()
{
List<CoinMarket> coinMarket = new List<CoinMarket>();
var URLWebAPI = "http://190.202.54.19/wsZeus/api/Account/Markets/Get";
try
{
using (var Client = new System.Net.Http.HttpClient())
{
var JSON = Client.GetStringAsync(URLWebAPI);
coinMarket = (List<CoinMarket>)Newtonsoft.Json.JsonConvert.DeserializeObject(JSON.Result);
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(#" ERROR {0}", ex.Message);
}
return coinMarket;
}
It is throwing and i do not know why. It looks like there is something wrong with the serialization part. But i verified it.
You are using json deserializer incorrectly. DeserializeObject returns custom object which is not castable to your List<T>. This output:
Newtonsoft.Json.Linq.JArray
SO20171129.CoinData[]
System.Collections.Generic.List`1[SO20171129.CoinData]
is the result of this code.
class Program
{
static void Main(string[] args)
{
// returns Newtonsoft.Json.Linq.JArray
var coinMarket = Newtonsoft.Json.JsonConvert.DeserializeObject(File.ReadAllText("get.json"));
Console.WriteLine(coinMarket.GetType());
// returns array of CoinData
var coinMarketTyped = Newtonsoft.Json.JsonConvert.DeserializeObject<CoinData[]>(File.ReadAllText("get.json"));
Console.WriteLine(coinMarketTyped.GetType());
// returns List of CoinData
var coinMarketTyped2 = Newtonsoft.Json.JsonConvert.DeserializeObject<List<CoinData>>(File.ReadAllText("get.json"));
Console.WriteLine(coinMarketTyped2.GetType());
}
}
public class CoinData
{
public string id { get; set; }
public string name { get; set; }
public string symbol { get; set; }
public string rank { get; set; }
public string price_usd { get; set; }
public string price_btc { get; set; }
public string __invalid_name__24h_volume_usd { get; set; }
public string market_cap_usd { get; set; }
public string available_supply { get; set; }
public string total_supply { get; set; }
public string percent_change_1h { get; set; }
public string percent_change_24h { get; set; }
public string percent_change_7d { get; set; }
public string last_updated { get; set; }
}
My guess is that your json structure members do not match the CoinMarket class members.
What I would do is to copy the json result and generate the corresponding CoinMarket class on the following website: http://json2csharp.com/
It will output the right CoinMarket class for you.
public class CoinMarket
{
public string id { get; set; }
public string name { get; set; }
public string symbol { get; set; }
public string rank { get; set; }
public string price_usd { get; set; }
public string price_btc { get; set; }
[JsonProperty("24h_volume_usd")]
public string h_volume_usd { get; set; }
public string market_cap_usd { get; set; }
public string available_supply { get; set; }
public string total_supply { get; set; }
public string percent_change_1h { get; set; }
public string percent_change_24h { get; set; }
public string percent_change_7d { get; set; }
public string last_updated { get; set; }
}
}
This is my CoinMarket Class

LDAP SearchResponse to Json C#

I am using a C# LdapConnection to get a SearchResponse at work. I can get the SearchResponse into a Json string, but am unable to put that Json string into an object class with properties which mimic the SearchResponse. The Json string is properly formatted. Am I using the Newtonsoft.Json library in the wrong way? Is there a better way to do this? My only requirements are that I get a SearchResponse into my object class (DirectoryEntity) so I can use it from there.
My Console Application:
class Program
{
static void Main(string[] args)
{
LdapClient client = new LdapClient();
List<LdapSearchResponseModel> list = new List<LdapSearchResponseModel>();
string query = "(|(uupid=name1)(uupid=name2))";
string[] attributes = new string[] { };
string host = "id.directory.univ";
int port = 1234;
SearchResponse response = client.RawQuery(query, attributes, host, port);
string json = JsonConvert.SerializeObject(response);
var test = JsonConvert.DeserializeObject<DirectoryEntities>(json);
}
}
My DirectoryEntity Class:
public class DirectoryEntity
{
public string EntityDN { get; set; }
public int MailStop { get; set; }
public List<string> UniversityAffiliation { get; set; }
public int UniversityId { get; set; }
public string GivenName { get; set; }
public string Title { get; set; }
public string PasswordState { get; set; }
public string MiddleName { get; set; }
public string AccountState { get; set; }
public int Uid { get; set; }
public string Mail { get; set; }
public string MailPreferredAddress { get; set; }
public DateTime DateOfBirth { get; set; }
public List<string> GroupMembership { get; set; }
public string DegreeType { get; set; }
public int ClassLevelCode { get; set; }
public string AuthId { get; set; }
public string Major { get; set; }
public string ClassLevel { get; set; }
public bool SupressDisplay { get; set; }
public string UnderGraduateLevel { get; set; }
public string ObjectClass { get; set; }
public int DepartmentNumber { get; set; }
public List<string> EduPersonAffiliation { get; set; }
public string LocalPostalAddress { get; set; }
public string Uupid { get; set; }
public string LocalPhone { get; set; }
public string TelephoneNumber { get; set; }
public string Department { get; set; }
public string Sn { get; set; }
}
My DirectoryEntities Class:
public class DirectoryEntities
{
public List<DirectoryEntity> Entities { get; set; }
public int Count { get; set; }
}
Have you tried explicitly defining a default constructor for the DirectoryEntity class? I believe that Newtonsoft requires objects to have a default constructor before they can be deserialized. Try adding this to the DirectoryEntity class:
public DirectoryEntity() { }

How do you get the selling_price? (Xamarin Forms)

This is my code:
dynamic resultObject = JsonConvert.DeserializeObject(Result);
string final = JsonConvert.SerializeObject(resultObject);
This my the result of final (JSON):
How do get the selling_price field? like doing final.selling_price?
My class:
public class ItemPriceJson {
public string item_price_id { get; set; }
public string item_code { get; set; }
public string item_desc { get; set; }
public string trnx_unit { get; set; }
public string price_level_id { get; set; }
public string price_level_code { get; set; }
public string selling_price { get; set; }
} // itemPriceJson
You're not deserializing the json to a dynamic object properly. First of all, it's an array, not an object.
So, try it like this:
dynamic resultObject = JArray.Parse(Result); //Dynamic object.
var sellingPrice = resultObject[0].selling_price; //Get the selling price. Could also use some casting here.
You should change your class to
public class ItemPriceJson {
public int item_price_id { get; set; }
public string item_code { get; set; }
public string item_desc { get; set; }
public string trnx_unit { get; set; }
public int price_level_id { get; set; }
public string price_level_code { get; set; }
public int selling_price { get; set; }
} // itemPriceJson
and deserialize it with
var results = JsonConvert.DeserializeObject<List<ItemPriceJson>>( Result );
because the json result contains an array of objects and so you need a collection for deserialization
Create a POCO class which describes the object for example;
public class MyItemObject
{
public string item_price_id { get; set; }
public string item_desc { get; set; }
public string trnx_unit { get; set; }
}
Then use JsonConvert to deserialize a instance of the object.
var result = JsonConvert.DeserializeObject<MyItemObject>(json);
EDIT
As json is a list/collection deserialize as a list type;
var listResult = JsonConvert.DeserializeObject<List<MyItemObject>>(json);
public class ItemPriceJson {
public string item_price_id { get; set; }
public string item_code { get; set; }
public string item_desc { get; set; }
public string trnx_unit { get; set; }
public string price_level_id { get; set; }
public string price_level_code { get; set; }
public string selling_price { get; set; }
}
And you can use the Newtonsoft json library
var result = JsonConvert.DeserializeObject<List<ItemPriceJson>>(jsonstring);

Error during deserialize JSON windows phone 8

I got a api that returns this JSON code:
[{"startDate":1409553000000,
"endDate":1409570100000,
"moduleCode":"#SPLUS0EBB2C",
"activityDescription":"User Interface Design (Tjuna)","staffMembers":[],
"locations":[{"id":"E404A902125255D3330455204193CC29","name":"HAA-H1-21","key":"14124","capacity":24,"url":null,"avoidConcurrencyLocationIds":[]}],
"studentSets":["INF3s","INF4a"],
"activityTypeName":"Other","activityTypeDescription":null,"notes":null,"highlighted":false,
"timetableKeys":["2013!studentsetgroup!9EEA55042B995043A2BC5739BF428E07"]}]
To deserialize I have this code:
var responseObject = await JsonConvert.DeserializeObjectAsync<Apicalls.Rooster>(json);
class Rooster
{
public string startDate { get; set; }
public string endDate { get; set; }
public string activityDescription { get; set; }
public locations[] locations { get; set; }
public string studentSets { get; set; }
}
public class locations
{
public string name { get; set; }
}
Everytime I try to deserialize it gives a error that it's not possible to deserialize the json code. Can anyone help me with this problem?
Rooster
public class Rooster
{
public long startDate { get; set; }
public long endDate { get; set; }
public string moduleCode { get; set; }
public string activityDescription { get; set; }
public List<object> staffMembers { get; set; }
public List<Location> locations { get; set; }
public List<string> studentSets { get; set; }
public string activityTypeName { get; set; }
public object activityTypeDescription { get; set; }
public object notes { get; set; }
public bool highlighted { get; set; }
public List<string> timetableKeys { get; set; }
}
Location
public class Location
{
public string id { get; set; }
public string name { get; set; }
public string key { get; set; }
public int capacity { get; set; }
public object url { get; set; }
public List<object> avoidConcurrencyLocationIds { get; set; }
}
Code:
var responseObject =
await JsonConvert.DeserializeObjectAsync<List<Apicalls.Rooster>>(json);
Demo

Unable to deserialize the JSON string to object

Guyz
I am trying to parse a JSON string into object. I have the below entity in which I am parsing the JSON string
public class Room : BaseEntity
{
public string Name { get; set; }
public string EmailAddress { get; set; }
public string RoomListEmailAddress { get; set; }
public string MinimumXCoordinateInMap { get; set; }
public string MinimumYCoordinateInMap { get; set; }
public string MaximumXCoordinateInMap { get; set; }
public string MaximumYCoordinateInMap { get; set; }
public string RoomCapacity { get; set; }
public List<RoomImage> RoomImage { get; set; }
public string FloorName { get; set; }
public string CreatedDate { get; set; }
public string CreatedId { get; set; }
public string LastUpdatedDate { get; set; }
public string LastUpdatedId { get; set; }
public InternalOnly InternalOnly { get; set; }
//public List<Equipment> Equipment { get; set; }
public override string ToString()
{
return this.Name;
}
}
public class RoomImage : BaseEntity
{
public string ImagePath { get; set; }
public string ImageType { get; set; }
public string CreatedDate { get; set; }
public string CreatedId { get; set; }
public string LastUpdatedDate { get; set; }
public string LastUpdatedId { get; set; }
public InternalOnly InternalOnly { get; set; }
}
public class InternalOnly : BaseEntity
{
public string RoomId { get; set; }
public string FloorId { get; set; }
}
public class BaseEntity
{
}
I am using below method to parse the string into object
public static T ParseObjectToJSON<T>(string responseText)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
using (MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(responseText)))
{
var rootObject = serializer.ReadObject(stream);
//return Convert.ChangeType(rootObject,typeof(T),System.Globalization.CultureInfo.CurrentCulture.TextInfo);
return (T)rootObject;
}
}
Below is the JSON string which I am trying to parse
https://docs.google.com/document/d/1k81M_UxIrXpHUPQNDUCHDfNw1wY7LM4mAaXjwpYMshk/edit?usp=sharing
The below json string is working
https://docs.google.com/document/d/1uQNwMmSyEZSolyxUVJl6gXzZPr6aRAf_WAogmUvVqt4/edit?usp=sharing
While parsing I get below error
The data contract type 'GAP.Entities.Room' cannot be deserialized because the member 'RoomImage' is not public. Making the member public will fix this error. Alternatively, you can make it internal, and use the InternalsVisibleToAttribute attribute on your assembly in order to enable serialization of internal members - see documentation for more details. Be aware that doing so has certain security implications.
Note- RoomImage is marked public in the entity class. I get this error only when JSON string contains RoomImage array string otherwise no erro.
Any help is highly appreciated.
Thanks
Vinod
You can download and deserialize an JSON using Newtonsoft.
You have to reference the following DLL, and after that you can try this:
List<Room> deserializedObj = (List<Room>)Newtonsoft.Json.JsonConvert.DeserializeObject(responseText, typeof(List<Room>));
The problem with your json is that if RoomImage has a single element, your service returns it as an object {} not as an array of objects [{}].
So If you want to use type-safe classes in your code(since dynamically accessing is also possible) you should pre-process your json before deserializing. Below code works (of course, as everybody says, using Json.Net)
string json = your__json__string
//PreProcess
var jobj = JObject.Parse(json);
foreach (var j in jobj["ObjectList"])
{
if (!(j["RoomImage"] is JArray))
{
j["RoomImage"] = new JArray(j["RoomImage"]);
}
}
var obj = JsonConvert.DeserializeObject<RootObject>(jobj.ToString());
public class InternalOnly
{
public string RoomId { get; set; }
public string FloorId { get; set; }
}
public class RoomImage
{
public string ImagePath { get; set; }
public string ImageType { get; set; }
public string CreatedDate { get; set; }
public string CreatedId { get; set; }
public string LastUpdateDate { get; set; }
public string LastUpdateId { get; set; }
}
public class ObjectList
{
public string Name { get; set; }
public string EmailAddress { get; set; }
public string RoomListEmailAddress { get; set; }
public string MinimumXCoordinateInMap { get; set; }
public string MinimumYCoordinateInMap { get; set; }
public string MaximumXCoordinateInMap { get; set; }
public string MaximumYCoordinateInMap { get; set; }
public string RoomCapacity { get; set; }
public RoomImage[] RoomImage { get; set; }
public string FloorName { get; set; }
public string CreatedDate { get; set; }
public string CreatedId { get; set; }
public string LastUpdatedDate { get; set; }
public string LastUpdatedId { get; set; }
public string IsRestrictedRoom { get; set; }
public InternalOnly InternalOnly { get; set; }
public object Equipment { get; set; }
}
public class RootObject
{
public List<ObjectList> ObjectList { get; set; }
}
The property RoomImage is public but your class probably isn't.
Make sure the RoomImage class is also marked public. That should solve the problem.
Alternatively use a library like JSON.NET that can do this deserialization without the need for public classes.

Categories

Resources