Converting Json code to C# (numbers as keys) - c#

I get some json code from web services in Windows Phone 8. I generate my entities class thanks to the site json2csharp (http://json2csharp.com/). But there is a web service that has strange json code, like this. There is numbering as keys (0,1,2):
{
"service": "MainMapService",
"func": "getPlacesByAxes",
"result": {
"0": {
"id": "13478",
"date": "0",
"id_cat": "1",
"id_cat_sub": "0",
"id_user": "0",
},
"2": {
"id": "23272",
"date": "0",
"id_cat": "1",
"id_cat_sub": "0",
"id_user": "667"
},
"1": {
"id": "21473",
"date": "0",
"id_cat": "1",
"id_cat_sub": "0",
"id_user": "0"
}
},
"args": [
"1",
"50.8",
"4.5",
"1"
]
}
And json2csharp generates classes like this... Each class for a number:
public class __invalid_type__0
{
public string id { get; set; }
public string date { get; set; }
public string id_cat { get; set; }
public string id_cat_sub { get; set; }
public string id_user { get; set; }
}
public class __invalid_type__2
{
public string id { get; set; }
public string date { get; set; }
public string id_cat { get; set; }
public string id_cat_sub { get; set; }
public string id_user { get; set; }
}
public class __invalid_type__1
{
public string id { get; set; }
public string date { get; set; }
public string id_cat { get; set; }
public string id_cat_sub { get; set; }
public string id_user { get; set; }
}
public class Result
{
public __invalid_type__0 __invalid_name__0 { get; set; }
public __invalid_type__2 __invalid_name__2 { get; set; }
public __invalid_type__1 __invalid_name__1 { get; set; }
}
public class RootObject
{
public string service { get; set; }
public string func { get; set; }
public Result result { get; set; }
public List<string> args { get; set; }
}
So, the problem comes from the numbering keys and there may be several numbers. Do you know how can I resolve this? I can't change the Json code...
Thank you in advance

This is far from elegant, but give it a try.
So, what is my idea:
I have created two classes
RootObject helper
public class YourJsonClass
{
public string service { get; set; }
public string func { get; set; }
public dynamic result { get; set; }
public string[] args { get; set; }
}
result helper
public class Item
{
public string id { get; set; }
public string date { get; set; }
public string id_cat { get; set; }
public string id_cat_sub { get; set; }
public string id_user { get; set; }
}
I'm using newtonsoft json
var m_res = JsonConvert.DeserializeObject<YourJsonClass>(YourJsonResponce);
foreach (dynamic numb in m_res.result)
{
string m_name = numb.Name; // it will be "1", "0" or whatever
string h = numb.Value.ToString();
var m_value = JsonConvert.DeserializeObject<Item>(h);
}
... indeed there are better ways, but i hope this will help (:

Related

Deserialize JSON to List

I have this Json:
{
"trades": [
{
"id": "4004",
"instrument": "EUR_USD",
"price": "1.08938",
"openTime": "2020-02-26T12:15:32.309973340Z",
"initialUnits": "1",
"initialMarginRequired": "0.0363",
"state": "OPEN",
"currentUnits": "1",
"realizedPL": "0.0000",
"financing": "0.0000",
"dividendAdjustment": "0.0000",
"unrealizedPL": "-0.0026",
"marginUsed": "0.0362",
"takeProfitOrder": {
"id": "4005",
"createTime": "2020-02-26T12:15:32.309973340Z",
"type": "TAKE_PROFIT",
"tradeID": "4004",
"price": "1.09099",
"timeInForce": "GTC",
"triggerCondition": "DEFAULT",
"state": "PENDING"
}
}
],
"lastTransactionID": "4010"
}
And Classes:
public class TakeProfitOrder
{
public string id { get; set; }
public string createTime { get; set; }
public string type { get; set; }
public string tradeID { get; set; }
public string price { get; set; }
public string timeInForce { get; set; }
public string triggerCondition { get; set; }
public string state { get; set; }
}
public class Trade
{
public string id { get; set; }
public string instrument { get; set; }
public string price { get; set; }
public string openTime { get; set; }
public string initialUnits { get; set; }
public string initialMarginRequired { get; set; }
public string state { get; set; }
public string currentUnits { get; set; }
public string realizedPL { get; set; }
public string financing { get; set; }
public string dividendAdjustment { get; set; }
public string unrealizedPL { get; set; }
public string marginUsed { get; set; }
public TakeProfitOrder takeProfitOrder { get; set; }
}
public class RootObject
{
public List<Trade> trades { get; set; }
public string lastTransactionID { get; set; }
}
I deserialize with :
var result = JsonConvert.DeserializeObject<RootObject>(Json);
var price = result.trades.Select(p => p.price).ToList();
price.ForEach(Console.WriteLine);
It works. I can access "price" in "trades", but I do not know how to access the "price" in "takeProfitOrder". I need the value of "price" from "takeProfitOrder" in to a list. I am sure it is something very simple but I cannot figure out how to do it, even after looking at some similar examples.
Can somebody please help me?
It's simple
result.trades.Select(p => p.takeProfitOrder.price)
You should understand better from this example
foreach (Trade trade in result.trades)
{
TakeProfitOrder takeProfitOrder = trade.takeProfitOrder;
Console.WriteLine(takeProfitOrder.price);
}

Parsing JSON with LINQ into List of Objects

I'm a little confused on the best way to parse the following JSON structure.
{
"featured": {
"id": 15,
"title": "media 1 -> 7",
"description": "test1",
"short_description": "test1",
"rating_avg": 0.0,
"image": "//d25xdrj7gd7wz1.cloudfront.net/covers/1603/1452024324.jpg"
},
"categories": [
{
"id": 1,
"title": "category 0",
"description": null,
"position": 0,
"media": [
{
"id": 1,
"title": "media 0 -> 0",
"description": "test1",
"short_description": "test1",
"rating_avg": 0.0,
"image": "//d25xdrj7gd7wz1.cloudfront.net/covers/1603/1452024324.jpg",
"category_media": {
"position": 0,
"category_id": 1,
"media_id": 1,
"id": 1
}
}, ...
Basically I have an array of categories which contains an array of medias (the featured is for something else)
I am looking to return List and the Category object contains a List
and I created some models:
public class Category
{
public string Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public List<Media> MediaList { get; set; }
}
public class Media
{
public string Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string ShortDescription { get; set; }
public string Image { get; set; }
}
..and I am supposed to use Newtonsoft?
I looked at the following example: Deserializing Partial JSON Fragments but I would think I don't need to convert from JToken -> Category ... etc. In other words, I would think it would be easy to just return my List.
I'm new to LINQ (I come from a python background) so I'm getting to know C#
Use This as your Model
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public partial class JsonModel
{
[JsonProperty("featured")]
public Featured Featured { get; set; }
[JsonProperty("categories")]
public List<Category> Categories { get; set; }
}
public partial class Category
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("description")]
public object Description { get; set; }
[JsonProperty("position")]
public long Position { get; set; }
[JsonProperty("media")]
public List<Featured> Media { get; set; }
}
public partial class Featured
{
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("short_description")]
public string ShortDescription { get; set; }
[JsonProperty("rating_avg")]
public long RatingAvg { get; set; }
[JsonProperty("image")]
public string Image { get; set; }
[JsonProperty("category_media", NullValueHandling = NullValueHandling.Ignore)]
public CategoryMedia CategoryMedia { get; set; }
}
public partial class CategoryMedia
{
[JsonProperty("position")]
public long Position { get; set; }
[JsonProperty("category_id")]
public long CategoryId { get; set; }
[JsonProperty("media_id")]
public long MediaId { get; set; }
[JsonProperty("id")]
public long Id { get; set; }
}
}
Then do this in your Class:
var info = JsonConvert.DeserializeObject<JsonModel>(json);
var featured = info.Featured;
var categories = info.Categories;
You don't need LINQ in this case unless you want to change the data structure. To parse json file to list you have to create a class that matches a structure of your file, like:
class DataModel
{
public Featured Featured { get; set; }
public List<Category> Categories { get;set; }
}
Also, please pay attention that you need to use attribute [JsonProperty(PropertyName="fieldName")] if property name in json is different from property name in class.
And finally, to parse the data use the following row:
var data = JsonConvert.DeserializeObject<DataModel>(jsonString);
Act as follow:
Update your models with:
public class Category
{
public string Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public List<Media> Media { get; set; }
}
public class Media
{
public string Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string ShortDescription { get; set; }
public string Image { get; set; }
}
public class Featured
{
public string Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Short_Description { get; set; }
}
And then make a model same as your JSON structure:
public class YOUR_MODEL
{
public Featured Featured { get; set; }
public List<Category> Categories { get;set; }
}
And then Descrilize your JSON to your object:
YOUR_MODELresults = JsonConvert.DeserializeObject<YOUR_MODEL>(YOUR_JSON);
To get your model you can use tool like :
https://jsonutils.com/ or http://json2csharp.com/
In case of need you can also validate json syntax with : https://jsonlint.com/ to get detailed errors.
With a slightly modified version of your example, I get :
public class CategoryMedia
{
public int position { get; set; }
public int category_id { get; set; }
public int media_id { get; set; }
public int id { get; set; }
}
public class Medium
{
public int id { get; set; }
public string title { get; set; }
public string description { get; set; }
public string short_description { get; set; }
public double rating_avg { get; set; }
public string image { get; set; }
public CategoryMedia category_media { get; set; }
}
public class Category
{
public int id { get; set; }
public string title { get; set; }
public object description { get; set; }
public int position { get; set; }
public IList<Medium> media { get; set; }
}
public class Featured
{
public int id { get; set; }
public string title { get; set; }
public string description { get; set; }
public string short_description { get; set; }
public double rating_avg { get; set; }
public string image { get; set; }
public IList<Category> categories { get; set; }
}
public class Example
{
public Featured featured { get; set; }
}
It spares a lot of time for creating models and it allows you to verify that you don't have typos in field names.
With this, you just have to deserialize your JSON sample to "Example" class, using the library of your choice. Newtonsoft Json is a very efficient classical !
Newtonsoft is the standard for doing work like this. So lets look at the best way to do this. First lets start with your json format and fix it so you can use the online tools available to create a good model structure:
[
{
"featured": {
"id": 15,
"title": "media 1 -> 7",
"description": "test1",
"short_description": "test1",
"rating_avg": 0.0,
"image": "//d25xdrj7gd7wz1.cloudfront.net/covers/1603/1452024324.jpg"
},
"categories": [
{
"id": 1,
"title": "category 0",
"description": null,
"position": 0,
"media": [
{
"id": 1,
"title": "media 0 -> 0",
"description": "test1",
"short_description": "test1",
"rating_avg": 0.0,
"image": "//d25xdrj7gd7wz1.cloudfront.net/covers/1603/1452024324.jpg",
"category_media": {
"position": 0,
"category_id": 1,
"media_id": 1,
"id": 1
}
}
]
}
]
}
]
Now if you plug that into http://json2csharp.com/, it will output a good model structure:
public class Featured
{
public int id { get; set; }
public string title { get; set; }
public string description { get; set; }
public string short_description { get; set; }
public double rating_avg { get; set; }
public string image { get; set; }
}
public class CategoryMedia
{
public int position { get; set; }
public int category_id { get; set; }
public int media_id { get; set; }
public int id { get; set; }
}
public class Medium
{
public int id { get; set; }
public string title { get; set; }
public string description { get; set; }
public string short_description { get; set; }
public double rating_avg { get; set; }
public string image { get; set; }
public CategoryMedia category_media { get; set; }
}
public class Category
{
public int id { get; set; }
public string title { get; set; }
public object description { get; set; }
public int position { get; set; }
public List<Medium> media { get; set; }
}
public class RootObject
{
public Featured featured { get; set; }
public List<Category> categories { get; set; }
}
Feel free to rename RootObject So now lets look are how you can deserialize your json into your model objects using Newtonsoft:
Firstly you need to get your json file into a string format, so lets say its a file on your computer or in your project, there is many ways to retrieve it, either using Assembly, or Directory methods. Once you have access to your json file, read out the contents and then using Newtonsoft method for deserialising:
var myString = File.ReadAllText(path)
var myObject = JsonConvert.DeserializeObject<RootObject>(myString);
And thats it:P

C# - How convert json string to class

How can I convert my json-string to class
this is my json
{
"$id": "1",
"Result": {
"$id": "2",
"dateTime": 23821964,
"list": [{
"$id": "3",
"UserId": 302,
"UID": "302_UID",
"Title": "شیدکو",
"Sender": "شیدکو",
"Answer": "",
"Comment": "test 2",
"ProductTitle": null,
"CommentId": 77,
"Logo": "http://example.com/Commercial/User/302/Logo/tmpF0BF.jpg",
"Date": 24302057,
"AnswerDate": -2123661683,
"AnswerEdit": false,
"CommentEdit": false,
"ForfeitCount": 0,
"RewardCount": 0,
"ThisCountReport": 2,
"Reported": [{
"$id": "4",
"BlockerId": 355,
"Title": "محتوای غیر اخلاقی",
"Date": -19527396,
"ForfeitCount": 0,
"RewardCount": 0
}, {
"$id": "5",
"BlockerId": 355,
"Title": "محتوای غیر مرتبط",
"Date": -19527382,
"ForfeitCount": 0,
"RewardCount": 0
}],
"Gem": 0
}, {
"$id": "6",
"UserId": 302,
"UID": "302_UID",
"Title": "شیدکو",
"Sender": "شیدکو",
"Answer": "",
"Comment": "test 2",
"ProductTitle": null,
"CommentId": 77,
"Logo": "http://example.com/Commercial/User/302/Logo/tmpF0BF.jpg",
"Date": 24302057,
"AnswerDate": -2123661683,
"AnswerEdit": false,
"CommentEdit": false
}]
},
"StatusCode": "Created",
"Description": null
}
And I do these step, but nothing happens
JObject json1 = JObject.Parse(strMyJson);
_CommentAdmindto flight = Newtonsoft.Json.JsonConvert.DeserializeObject<_CommentAdmindto>(json1.ToString());
_CommentAdmindto deserializedProduct = JsonConvert.DeserializeObject<_CommentAdmindto>(json);
_CommentAdmindto deserializedProduct1 = ConvertJsonToClass<_CommentAdmindto>(strMyJson);
JsonSerializer serializer = new JsonSerializer();
_CommentAdmindto p = (_CommentAdmindto)serializer.Deserialize(new JTokenReader(strMyJson), typeof(_CommentAdmindto));
And here is my class and function:
public static T ConvertJsonToClass<T>( string json)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
return serializer.Deserialize<T>(json);
}
}
public class _CommentAdmindto
{
public long dateTime { get; set; }
public IQueryable<CommentDtoAdmin> list { get; set; }
}
public class CommentDtoAdmin
{
public long UserId { get; set; }
public string UID { get; set; }
public string Title { get; set; }
public string Sender { get; set; }
public string Answer { get; set; }
public string Comment { get; set; }
public string ProductTitle { get; set; }
public long CommentId { get; set; }
public string Logo { get; set; }
public long Date { get; set; }
public long AnswerDate { get; set; }
public bool AnswerEdit { get; set; }
public bool CommentEdit { get; set; }
}
Your model should be similar to this (For invalid c# names, you can use JsonProperty attribute) :
public class Reported
{
[JsonProperty("$id")]
public string id { get; set; }
public int BlockerId { get; set; }
public string Title { get; set; }
public int Date { get; set; }
public int ForfeitCount { get; set; }
public int RewardCount { get; set; }
}
public class List
{
[JsonProperty("$id")]
public string id { get; set; }
public int UserId { get; set; }
public string UID { get; set; }
public string Title { get; set; }
public string Sender { get; set; }
public string Answer { get; set; }
public string Comment { get; set; }
public object ProductTitle { get; set; }
public int CommentId { get; set; }
public string Logo { get; set; }
public int Date { get; set; }
public int AnswerDate { get; set; }
public bool AnswerEdit { get; set; }
public bool CommentEdit { get; set; }
public int ForfeitCount { get; set; }
public int RewardCount { get; set; }
public int ThisCountReport { get; set; }
public List<Reported> Reported { get; set; }
public int Gem { get; set; }
}
public class Result
{
[JsonProperty("$id")]
public string id { get; set; }
public int dateTime { get; set; }
public List<List> list { get; set; }
}
public class RootObject
{
[JsonProperty("$id")]
public string id { get; set; }
public Result Result { get; set; }
public string StatusCode { get; set; }
public object Description { get; set; }
}
Now you can deserialize as
var result = JsonConvert.DeserializeObject<RootObject>(jsonstring);
BTW: http://json2csharp.com/ can help to guess your model when working with json.
You seem to be trying to deserialize in a lot of different ways but you don't have a full structure to actually match the json. You miss the outer class (representing the full object) and at least Newtonsoft.Json cannot deserialize to an IQueryable so I changed that to IEnumerable.
string strMyJson = "{\"$id\":\"1\",\"Result\":{\"$id\":\"2\",\"dateTime\":23826985,\"list\":[{\"$id\":\"3\",\"UserId\":302,\"UID\":\"302_UID\",\"Title\":\"شیدکو\",\"Sender\":\"شیدکو\",\"Answer\":\"\",\"Comment\":\"test 2\",\"ProductTitle\":null,\"CommentId\":77,\"Logo\":\"http://www.domain.com/Commercial/User/302/Logo/tmpF0BF.jpg\",\"Date\":24307078,\"AnswerDate\":-2123656662,\"AnswerEdit\":false,\"CommentEdit\":false,\"ForfeitCount\":0,\"RewardCount\":0,\"ThisCountReport\":2,\"Reported\":[{\"$id\":\"4\",\"BlockerId\":355,\"Title\":\"محتوای غیر اخلاقی\",\"Date\":-19527396,\"ForfeitCount\":0,\"RewardCount\":0},{\"$id\":\"5\",\"BlockerId\":355,\"Title\":\"محتوای غیر مرتبط\",\"Date\":-19527382,\"ForfeitCount\":0,\"RewardCount\":0}],\"Gem\":0},{\"$id\":\"6\",\"UserId\":302,\"UID\":\"302_UID\",\"Title\":\"شیدکو\",\"Sender\":\"شیدکو\",\"Answer\":\"\",\"Comment\":\"test 2\",\"ProductTitle\":null,\"CommentId\":77,\"Logo\":\"http://www.domain.com/Commercial/User/302/Logo/tmpF0BF.jpg\",\"Date\":24307078,\"AnswerDate\":-2123656662,\"AnswerEdit\":false,\"CommentEdit\":false}],\"StatusCode\":\"Created\",\"Description\":null}}";
var result = JsonConvert.DeserializeObject<Wrapper>(strMyJson);
with classes looking like this:
public class Wrapper
{
public _CommentAdmindto Result { get; set; }
}
public class _CommentAdmindto
{
public long dateTime { get; set; }
public IEnumerable<CommentDtoAdmin> list { get; set; }
}
CommentDtoAdmin is looking the same.
Though I must say that this only helps you with the deserialization.
Firstly, the $id" properties are synthetic properties added by Json.NET to track and preserve multiple references to the same object. For details, see PreserveReferencesHandling setting.
Thus, if you temporarily remove the "$id" properties, you can upload your JSON to http://json2csharp.com/ and get the following data model:
public class Reported
{
public int BlockerId { get; set; }
public string Title { get; set; }
public int Date { get; set; }
public int ForfeitCount { get; set; }
public int RewardCount { get; set; }
}
public class CommentDtoAdmin
{
public int UserId { get; set; }
public string UID { get; set; }
public string Title { get; set; }
public string Sender { get; set; }
public string Answer { get; set; }
public string Comment { get; set; }
public object ProductTitle { get; set; }
public int CommentId { get; set; }
public string Logo { get; set; }
public int Date { get; set; }
public int AnswerDate { get; set; }
public bool AnswerEdit { get; set; }
public bool CommentEdit { get; set; }
public int ForfeitCount { get; set; }
public int RewardCount { get; set; }
public int ThisCountReport { get; set; }
public List<Reported> Reported { get; set; }
public int Gem { get; set; }
}
public class Result
{
public int dateTime { get; set; }
public List<CommentDtoAdmin> list { get; set; }
}
public class RootObject
{
public Result Result { get; set; }
public string StatusCode { get; set; }
public string Description { get; set; }
}
I then modified the returned model as follows:
I used the name CommentDtoAdmin for the list type.
I set the type of the Description property to string.
Now your JSON can be deserialized and re-serialized as follows:
var settings = new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
};
var root = JsonConvert.DeserializeObject<RootObject>(json1, settings);
var json2 = JsonConvert.SerializeObject(root, Formatting.Indented, settings);
Note that Json.NET has no built-in logic for deserializing the interface IQueryable<T> to a concrete type, so I had to leave the property as public List<CommentDtoAdmin> list { get; set; }. You can always generate a queryable from the list using AsQueryable():
var queryable = root.Result.list.AsQueryable();
Sample fiddle.
I think you json string does not have correct syntax. It looks like a ']' (end of Array) and a final '}' is missing.
That's what the Visual Studio editor told me when making a json file out of your string after removing all the '\'

Convert Json String to C# Object List

I want to convert a json string to a Object list. Please help me. it would be more helpful if done by NewtonJson.
I tried, but its not working. I dont want all the values of that json. just which are mentioned in the MatrixModel
This is a Object
public class MatrixModel
{
public string S1 { get; set; }
public string S2 { get; set; }
public string S3 { get; set; }
public string S4 { get; set; }
public string S5 { get; set; }
public string S6 { get; set; }
public string S7 { get; set; }
public string S8 { get; set; }
public string S9 { get; set; }
public string S10 { get; set; }
public int ScoreIfNoMatch { get; set; }
}
This is the Json String
"[
{
"Question": {
"QuestionId": 49,
"QuestionText": "Whats your name?",
"TypeId": 1,
"TypeName": "MCQ",
"Model": {
"options": [
{
"text": "Rahul",
"selectedMarks": "0"
},
{
"text": "Pratik",
"selectedMarks": "9"
},
{
"text": "Rohit",
"selectedMarks": "0"
}
],
"maxOptions": 10,
"minOptions": 0,
"isAnswerRequired": true,
"selectedOption": "1",
"answerText": "",
"isRangeType": false,
"from": "",
"to": "",
"mins": "02",
"secs": "04"
}
},
"CheckType": "",
"S1": "",
"S2": "",
"S3": "",
"S4": "",
"S5": "",
"S6": "",
"S7": "",
"S8": "",
"S9": "Pratik",
"S10": "",
"ScoreIfNoMatch": "2"
},
{
"Question": {
"QuestionId": 51,
"QuestionText": "Are you smart?",
"TypeId": 3,
"TypeName": "True-False",
"Model": {
"options": [
{
"text": "True",
"selectedMarks": "7"
},
{
"text": "False",
"selectedMarks": "0"
}
],
"maxOptions": 10,
"minOptions": 0,
"isAnswerRequired": false,
"selectedOption": "3",
"answerText": "",
"isRangeType": false,
"from": "",
"to": "",
"mins": "01",
"secs": "04"
}
},
"CheckType": "",
"S1": "",
"S2": "",
"S3": "",
"S4": "",
"S5": "",
"S6": "",
"S7": "True",
"S8": "",
"S9": "",
"S10": "",
"ScoreIfNoMatch": "2"
}
]"
You can use json2csharp.com to Convert your json to object model
Go to json2csharp.com
Past your JSON in the Box.
Clik on Generate.
You will get C# Code for your object model
Deserialize by var model = JsonConvert.DeserializeObject<RootObject>(json); using NewtonJson
Here, It will generate something like this:
public class MatrixModel
{
public class Option
{
public string text { get; set; }
public string selectedMarks { get; set; }
}
public class Model
{
public List<Option> options { get; set; }
public int maxOptions { get; set; }
public int minOptions { get; set; }
public bool isAnswerRequired { get; set; }
public string selectedOption { get; set; }
public string answerText { get; set; }
public bool isRangeType { get; set; }
public string from { get; set; }
public string to { get; set; }
public string mins { get; set; }
public string secs { get; set; }
}
public class Question
{
public int QuestionId { get; set; }
public string QuestionText { get; set; }
public int TypeId { get; set; }
public string TypeName { get; set; }
public Model Model { get; set; }
}
public class RootObject
{
public Question Question { get; set; }
public string CheckType { get; set; }
public string S1 { get; set; }
public string S2 { get; set; }
public string S3 { get; set; }
public string S4 { get; set; }
public string S5 { get; set; }
public string S6 { get; set; }
public string S7 { get; set; }
public string S8 { get; set; }
public string S9 { get; set; }
public string S10 { get; set; }
public string ScoreIfNoMatch { get; set; }
}
}
Then you can deserialize as:
var model = JsonConvert.DeserializeObject<List<MatrixModel.RootObject>>(json);
public static class Helper
{
public static string AsJsonList<T>(List<T> tt)
{
return new JavaScriptSerializer().Serialize(tt);
}
public static string AsJson<T>(T t)
{
return new JavaScriptSerializer().Serialize(t);
}
public static List<T> AsObjectList<T>(string tt)
{
return new JavaScriptSerializer().Deserialize<List<T>>(tt);
}
public static T AsObject<T>(string t)
{
return new JavaScriptSerializer().Deserialize<T>(t);
}
}
using dynamic variable in C# is the simplest.
Newtonsoft.Json.Linq has class JValue that can be used. Below is a sample code which displays Question id and text from the JSON string you have.
string jsonString = "[{\"Question\":{\"QuestionId\":49,\"QuestionText\":\"Whats your name?\",\"TypeId\":1,\"TypeName\":\"MCQ\",\"Model\":{\"options\":[{\"text\":\"Rahul\",\"selectedMarks\":\"0\"},{\"text\":\"Pratik\",\"selectedMarks\":\"9\"},{\"text\":\"Rohit\",\"selectedMarks\":\"0\"}],\"maxOptions\":10,\"minOptions\":0,\"isAnswerRequired\":true,\"selectedOption\":\"1\",\"answerText\":\"\",\"isRangeType\":false,\"from\":\"\",\"to\":\"\",\"mins\":\"02\",\"secs\":\"04\"}},\"CheckType\":\"\",\"S1\":\"\",\"S2\":\"\",\"S3\":\"\",\"S4\":\"\",\"S5\":\"\",\"S6\":\"\",\"S7\":\"\",\"S8\":\"\",\"S9\":\"Pratik\",\"S10\":\"\",\"ScoreIfNoMatch\":\"2\"},{\"Question\":{\"QuestionId\":51,\"QuestionText\":\"Are you smart?\",\"TypeId\":3,\"TypeName\":\"True-False\",\"Model\":{\"options\":[{\"text\":\"True\",\"selectedMarks\":\"7\"},{\"text\":\"False\",\"selectedMarks\":\"0\"}],\"maxOptions\":10,\"minOptions\":0,\"isAnswerRequired\":false,\"selectedOption\":\"3\",\"answerText\":\"\",\"isRangeType\":false,\"from\":\"\",\"to\":\"\",\"mins\":\"01\",\"secs\":\"04\"}},\"CheckType\":\"\",\"S1\":\"\",\"S2\":\"\",\"S3\":\"\",\"S4\":\"\",\"S5\":\"\",\"S6\":\"\",\"S7\":\"True\",\"S8\":\"\",\"S9\":\"\",\"S10\":\"\",\"ScoreIfNoMatch\":\"2\"}]";
dynamic myObject = JValue.Parse(jsonString);
foreach (dynamic questions in myObject)
{
Console.WriteLine(questions.Question.QuestionId + "." + questions.Question.QuestionText.ToString());
}
Console.Read();
Output from the code =>
Please make sure that all properties are both the getter and setter. In case, any property is getter only, it will cause the reverting the List to original data as the JSON string is typed.
Please refer to the following code snippet for the same:
Model:
public class Person
{
public int ID { get; set; }
// following 2 lines are cause of error
//public string Name { get { return string.Format("{0} {1}", First, Last); } }
//public string Country { get { return Countries[CountryID]; } }
public int CountryID { get; set; }
public bool Active { get; set; }
public string First { get; set; }
public string Last { get; set; }
public DateTime Hired { get; set; }
}
public class ModelObj
{
public string Str { get; set; }
public List<Person> Persons { get; set; }
}
Controller:
[HttpPost]
public ActionResult Index(FormCollection collection)
{
var data = new ModelObj();
data.Str = (string)collection.GetValue("Str").ConvertTo(typeof(string));
var personsString = (string)collection.GetValue("Persons").ConvertTo(typeof(string));
using (var textReader = new StringReader(personsString))
{
using (var reader = new JsonTextReader(textReader))
{
data.Persons = new JsonSerializer().Deserialize(reader, typeof(List<Person>)) as List<Person>;
}
}
return View(data);
}
If there is no explicit need for a class (model), you can also use dynamic
List<dynamic> models = JsonConvert.DeserializeObject<List<dynamic>>(jsonString);
And then use dot to access whatever fields you need
models[0].MyField
Try to change type of ScoreIfNoMatch, like this:
public class MatrixModel
{
public string S1 { get; set; }
public string S2 { get; set; }
public string S3 { get; set; }
public string S4 { get; set; }
public string S5 { get; set; }
public string S6 { get; set; }
public string S7 { get; set; }
public string S8 { get; set; }
public string S9 { get; set; }
public string S10 { get; set; }
// the type should be string
public string ScoreIfNoMatch { get; set; }
}
The variables/parameters within the class definition requires { get; set; }
I was using like a variable declaration (stupid of me, because it was working for other scenarios) without
{ get; set; }
Because of which, whatever I send from the JavaScript, it was not being received in the Action method. It was always getting null or empty model.
Once the {get; set;} is added, it worked like charm.
I hope it helps someone who is coming from VB6 style of programming line.

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type with complex and nested objects

I`m trying to build web api for complex object. For this aim I built the custom binder which deserialize this object from JSON.
My Customer Binder looks like:
var paramType = p_BindingContext.ModelType;
dynamic updatedParam = Activator.CreateInstance(paramType);
JsonReader reader = new JTokenReader(JObject.Parse
(p_ActionContext.Request.Content.ReadAsStringAsync().Result));
JObject jObject = JObject.Load(reader);
JsonSerializer serializer = new JsonSerializer();
serializer.Populate(jObject.CreateReader(), updatedParam);//Here the exception thorws
p_BindingContext.Model = updatedParam;
The object to serialize is very comlex:
public class ModelRegisterUserRequest{
public ModelUser User { get; set; }
public CampaignItem CampaignWithChosenProposal { get; set; }
public string ValidationToken { get; set; }
public string IVRToken { get; set; }
public string DealerID { get; set; }
public string SalePersonID { get; set; }
}
public class CampaignItem
{
public List<BannerItem> Banners { get; set; }
public string Code { get; set; }
public string CustomerInstruction { get; set; }
public string InfoLink { get; set; }
public string LobbySubTitle { get; set; }
public string LobbyTitle { get; set; }
public string MoreText { get; set; }
public uint NumOfColumns { get; set; }
public uint NumOfRows { get; set; }
public string OriginString { get; set; }
public int OriginInt { get; set; }
public List<ProposalItem> Proposals { get; set; }
public string RegulationsInfoLink { get; set; }
public string ServiceType { get; set; }
public string SubTitle { get; set; }
public string SWDefault { get; set; }
public string Title { get; set; }
}
public partial class ProposalItem
{
public List<string> EquipmentsCode { get; set; }
public string FeatureCode { get; set; }
public string InvalidReason { get; set; }
public bool IsExistsMoreInfo { get; set; }
public bool IsValid { get; set; }
public string LeadCode { get; set; }
public int ParamCombinationCode { get; set; }
public string ProductCode { get; set; }
public string ProductCombinationCode { get; set; }
public string ProposalCode { get; set; }
public List<ColumnItem> Columns { get; set; }
public List<MoreInfoItem> MoreInfoList { get; set; }
public List<string> PricePlans { get; set; }
public string ProductName { get; set; }
}
The Json is created with JSON.stringify command from Javascript code and look like :
{
"ValidationToken": "1cc6cca8-44d5-4042-af37-de6a0d198d17",
"AppID": "TST",
"campaignWithChosenProposal": {
"Banners": [
{
"LocationCodeString": "ManagerTab",
"LocationCodeInt": 256,
"MediaUrl": "BANNER 10"
}
],
"Code": "CAMP221",
"CustomerInstruction": "-1",
"InfoLink": "http://test.aspx",
"LobbySubTitle": "",
"LobbyTitle": "",
"MoreText": "",
"NumOfColumns": 0,
"NumOfRows": 0,
"OriginString": "INT",
"OriginInt": 4,
"Proposals": [
[
{
"EquipmentsCode": [
"5455"
],
"FeatureCode": "BE5455",
"InvalidReason": "",
"IsExistsMoreInfo": true,
"IsValid": true,
"LeadCode": "3792956510",
"ParamCombinationCode": 0,
"ProductCode": "OANTIVRP2",
"ProductCombinationCode": "0",
"ProposalCode": "291600010201C8F83661D5B82FD5F3603967588B7A72",
"Columns": [
{
"Content": ""
},
{
"Content": ""
},
{
"Content": ""
},
{
"Content": ""
},
{
"Content": ""
},
{
"Content": ""
}
],
"MoreInfoList": [
{
"Content": "3",
"MoreInfoTypesString": "LicenseFrom",
"MoreInfoTypesInt": 16
},
{
"Content": "3",
"MoreInfoTypesString": "LicenseTo",
"MoreInfoTypesInt": 32
},
{
"Content": "4.3",
"MoreInfoTypesString": "PricePeriod1",
"MoreInfoTypesInt": 64
}
],
"PricePlans": [
"O2"
],
"ProductName": ""
}
]
],
"RegulationsInfoLink": "http://www.test.aspx",
"ServiceType": "TST",
"SubTitle": "",
"SWDefault": "1",
"Title": ""
},
"User": {
"CurrentLicenseNumber": 0,
"CustomerID": "21670106",
"FirstName": "",
"LastName": "",
"RequestedLicenseNumber": "3",
"SubscriberPhoneNumber": "035448428",
"IdentityNumber": "058470",
"Email": "alexanrbe#gmail.com",
"RegistrationStatus": "NOTREGISTERED"
},
"SalePersonID": "3178364",
}
The Exception is thrown on serilization row and looks like:
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type WebAPI.Models.Entities.Campaigns.CampaignObjects.ProposalItem' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly.
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array.
I spent nights for resolve this exception but did not find any solutions
Also the solutions on this site are excisted but not supports such complex problem.
https://stackoverflow.com/questions/11126242/using-jsonconvert-deserializeobject-to-deserialize-json-to-a-c-sharp-poco-class
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type
Somebody met such JSON unexpected behaiviour and could help?
Thanks
According to your JSON data, the objects that you need to map to have to look like this (unless you have your own JsonDeserializer of course):
public class Banner
{
public string LocationCodeString { get; set; }
public int LocationCodeInt { get; set; }
public string MediaUrl { get; set; }
}
public class CampaignWithChosenProposal
{
public List<Banner> Banners { get; set; }
public string Code { get; set; }
public string CustomerInstruction { get; set; }
public string InfoLink { get; set; }
public string LobbySubTitle { get; set; }
public string LobbyTitle { get; set; }
public string MoreText { get; set; }
public int NumOfColumns { get; set; }
public int NumOfRows { get; set; }
public string OriginString { get; set; }
public int OriginInt { get; set; }
public List<List<>> Proposals { get; set; }
public string RegulationsInfoLink { get; set; }
public string ServiceType { get; set; }
public string SubTitle { get; set; }
public string SWDefault { get; set; }
public string Title { get; set; }
}
public class User
{
public int CurrentLicenseNumber { get; set; }
public string CustomerID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string RequestedLicenseNumber { get; set; }
public string SubscriberPhoneNumber { get; set; }
public string IdentityNumber { get; set; }
public string Email { get; set; }
public string RegistrationStatus { get; set; }
}
public class RootObject
{
public string ValidationToken { get; set; }
public string AppID { get; set; }
public CampaignWithChosenProposal campaignWithChosenProposal { get; set; }
public User User { get; set; }
public string SalePersonID { get; set; }
}
Here is a really cool tool (json2csharp) to help you out.

Categories