Hello I'm trying to deserialize the following json in c#:
{
"Labels":[
{
"DeviceID":9,
"Disabled":false,
"Id":0,
"Internal":"1#CB_I_AllCloseCheck",
"Label":"CB_I_AllCloseCheck",
"MAddress":0,
"Mask":2147483648,
"ModuleID":4,
"Offset":0,
"Position":1,
"SectionID":0,
"Type":16
}
]
}
With the following code line:
Labels myDeserializedObjList = (Labels)JsonConvert.DeserializeObject(sub, typeof(Labels));
The string sub contains this json like a string. Where my class Labels is the following:
public class Labels
{
public string DeviceID { get; set; }
public string Disabled { get; set; }
public string IValue { get; set; }
public string Id { get; set; }
public string Internal { get; set; }
public string Label { get; set; }
public string MAddress { get; set; }
public string Mask { get; set; }
public string ModuleID { get; set; }
public string Offset { get; set; }
public string Position { get; set; }
public string SectionID { get; set; }
public string Type { get; set; }
}
But the result of this operation is all my atributes equal to null. Anyone knows what I'm doing wrong?
At the moment your root object is just that: an object. It's not an array. Its only property (Labels) is an array.
You should add an extra "root object" class:
public class LabelsContainer
{
public IList<Labels> Labels {get;set;}
}
And then deserialize to that:
var labelsContainer = Newtonsoft.Json.JsonConvert.DeserializeObject<LabelsContainer>(data);
var labels = labelsContainer?.Labels;
The JSON string shows an object with a Labels property that contains an array of labels. You need to try something like :
class LabelsDTO
{
public Labels[] Labels{get;set;}
}
...
var dto = JsonConvert.DeserializeObject<LabelsDTO>(sub);
for (var label in dto.Labels)
{
...
}
Related
I have the "json" mentioned below. "changes" property is changeable
{"sort":[{"field":"recid","direction":"desc"}],"changes":[{"recid":2084,"LokasyonAdresi":"211","LokasyonAdi":"111"}],"action":"save"}
When I convert json to c# classes, the following classes are created.
public class Sort
{
public string field { get; set; }
public string direction { get; set; }
}
public class Change
{
public int recid { get; set; }
public string LokasyonAdresi { get; set; }
public string LokasyonAdi { get; set; }
}
public class Root
{
public List<Sort> sort { get; set; }
public List<Change> changes { get; set; }
public string action { get; set; }
}
I want the class I want to convert to be like this. How can I customize?
public class Root
{
[JsonPropertyName("sort")]
public IList<Sort> Sort { get; set; }
[JsonPropertyName("action")]
public string Action { get; set; }
[JsonPropertyName("changes")]
public IDictionary<string, object> Changes { get; set; }
}
try this code
var jsonParsed = JObject.Parse(json);
Dictionary<string,object> changes=((JArray)jsonParsed["changes"])
.SelectMany(x=> x.ToObject<Dictionary<string,object>>())
.ToDictionary(kvp=>kvp.Key,kvp=>kvp.Value);
List<Sort> sort= ((JArray) jsonParsed["sort"]).Select(x=> x.ToObject<Sort>()).ToList();
var data = new Root {
Action= (string) jsonParsed["action"],
Sort= sort,
Changes=changes
};
i have following javascript object it looks like json but when i parse it as json i am getting errors:
{
"1": {
"name": "Manheim Simulcast ",
"items": {
"2": {
"pos": "52",
"name": "NY - Manheim Albany",
"address": "",
"zip": "12201",
"coords": ""
}
}
}
}
and following classes:
public class auction_js_min
{
public auction_id auction_id { set; get; }
}
public class auction_id
{
public string name { set; get; }
public Items items { set; get; }
}
public class Items
{
public Sub_auction_id sub_auction_id { set; get; }
}
public class Sub_auction_id
{
public string pos { get; set; }
public string name { get; set; }
public string address { get; set; }
public string zip { get; set; }
public string coords { get; set; }
}
when i deserialize it to C# object im getting empty object:
auction_js_min obj = JsonConvert.DeserializeObject<auction_js_min>(auction_js);
is any idea how to fix it? javascript object is too big 87000 symbol and i want iterate over objects and check values.
I think what you're running into here is that your objects are numbered and you can't name a class with just number. In this case your model doesn't match your JSON so all you're going to get is null. You need to modify your model to match the JSON you have and then you can map that DTO model to something nicer to use in C#.
Here's an example model that deserializes your JSON:
public class auction_id
{
public string name { set; get; }
public IDictionary<int, Sub_auction_id> items { set; get; }
}
public class Sub_auction_id
{
public string pos { get; set; }
public string name { get; set; }
public string address { get; set; }
public string zip { get; set; }
public string coords { get; set; }
}
And then deserialize like so:
public void Deserialize()
{
var auction = JsonConvert.DeserializeObject<IDictionary<int, auction_id>>(json);
}
I think you can make use of JsonProperty here.
Usually these names are invalid but they could be parsed like this.
public class auction_js_min
{
[JsonProperty("1")]
public auction_id auction_id { set; get; }
}
public class auction_id
{
public string name { set; get; }
public Items items { set; get; }
}
public class Items
{
[JsonProperty("2")]
public Sub_auction_id sub_auction_id { set; get; }
}
public class Sub_auction_id
{
public string pos { get; set; }
public string name { get; set; }
public string address { get; set; }
public string zip { get; set; }
public string coords { get; set; }
}
Thats because of single quotes. Both of the following will work:
If you know your object is correct, skip the string quotation and directly eval it:
eval({'1': {'name': 'Manheim Simulcast','items':{'2':{'pos': '52','name': 'NY - Manheim Albany','address': '','zip': '12201','coords': ''}}}})
Or use double quotes inside JSON and single quotes to make it a string likr this:
JSON.parse('{"1": {"name": "Manheim Simulcast","items":{"2":{"pos": "52","name": "NY - Manheim Albany","address": "","zip": "12201","coords": ""}}}}')
As far as parsing them to a C# object. It can be multiple things, need more details.
I trying to build Magic The Gathering card viewer and getting data from json. I have created json file, then copy all and paste special to my class to generate a model. In constructor using json parser I parsed object fine, but when I try to assign to that object property, so I can make method retrieve all cards. But when I trying to do that it says that I can't implicitly assign. I try to assign Cards = cardsCollection; that where it throws an error.
namespace MTGArena
{
public class Cards
{
public class Rootobject
{
static Rootobject()
{
using (StreamReader file = new StreamReader("cards.json"))
{
string json = file.ReadToEnd();
Rootobject cardsCollection = JsonConvert.DeserializeObject<Rootobject>(json);
Cards = cardsCollection;
}
}
public static List<Card> Cards { get; set; }
public static List<Card> GetCards()
{
return Cards;
}
}
}
public class Card
{
public string name { get; set; }
public string set { get; set; }
public Images images { get; set; }
public string type { get; set; }
public string[] cost { get; set; }
public int cmc { get; set; }
public string rarity { get; set; }
public string cid { get; set; }
public int?[] frame { get; set; }
public string artist { get; set; }
public string dfc { get; set; }
public bool collectible { get; set; }
public bool craftable { get; set; }
public int dfcId { get; set; }
public int rank { get; set; }
public string grpId { get; set; }
}
public class Images
{
public string small { get; set; }
public string normal { get; set; }
public string large { get; set; }
public string art_crop { get; set; }
}
}
Change the line:
Rootobject cardsCollection = JsonConvert.DeserializeObject<Rootobject>(json);
for:
var cardsCollection = JsonConvert.DeserializeObject<List<Card>>(json);
You need to use below syntax
IList<Card> cards = cardsCollection;
dont create empty Cards class. It has no use
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);
i made a jquery filter tool which returns to my server side filter data as json. i wanna convert it a C# class and also i want to convert any C# class to my json.
My json and it's mirror C# class below :
[{"field":{"label":"Category","value":"category"},"operator":{"label":"any of","value":"in"},"value":{"label":"(Family, Friends)","value":"1,2"}},{"field":{"label":"Age","value":"age"},"operator":{"label":">","value":"gt"},"value":{"label":"18","value":"18"}},{"field":{"label":"Firstname","value":"firstname"},"operator":{"label":"equals","value":"eq"},"value":{"label":"\"test\"","value":"test"}},{"field":{"label":"Lastname","value":"lastname"},"operator":{"label":"equals","value":"eq"},"value":{"label":"\"test2\"","value":"test2"}}]
C# mirror:
public class Field
{
public string label { get; set; }
public string value { get; set; }
}
public class Operator
{
public string label { get; set; }
public string value { get; set; }
}
public class Value
{
public string label { get; set; }
public string value { get; set; }
}
public class RootObject
{
public Field field { get; set; }
public Operator #operator { get; set; }
public Value value { get; set; }
}
i tried this way :
public class ViewFilter
{
public List<Field> Fields { get; set; }
public List<Operator> Operators { get; set; }
public List<Value> Values { get; set; }
public List<RootObject> RootObjects { get; set; }
}
public class Field
{
public string label { get; set; }
public string value { get; set; }
}
public class Operator
{
public string label { get; set; }
public string value { get; set; }
}
public class Value
{
public string label { get; set; }
public string value { get; set; }
}
public class RootObject
{
public Field field { get; set; }
public Operator #operator { get; set; }
public Value value { get; set; }
}
i tried :
var result = JsonConvert.DeserializeObject<List<ViewModel.ViewFilter>>(filter).ToList();
foreach (ViewModel.ViewFilter item in result)
{
}
When receiving the data, use the NewtonSoft JsonConvert class:
var serializerSettings = new JsonSerializerSettings
{ ContractResolver = new CamelCasePropertyNamesContractResolver() };
var fields = JsonConvert.DeserializeObject<List<RootObject>>(yourString, serializerSettings);
The yourString value being the string your are getting which contains your json data.
The CamelCasePropertyNamesContractResolver takes care of serializing objects names in camel case as its name indicates.