Deserialize Complex/Branched JSON and accessing branches - c#

I have a JSON response which i generated a model from. the JSON data has various branches with data as shown below.
{
"error": false,
"result": {
"customers": [
{
"district": null,
"feeder": "XXXXXXXXXXX",
"feeder_code": "XXXXXXXXXXX",
"transformer": "XXXXXXXXXXX",
"dss_code": "XXXXXXXXX",
"database_match": "XXXXXXXXXXX",
"accountnumber": "XXXXXXXXXXX",
"meterno": "XXXXXXXXXXX",
"oldaccountnumber": "XXXXXXXXXXX",
"odoo_account_number": "XXXXXXXXXXX",
"customername": "XXXXXXXXXXX",
"address": "XXXXXXXXXXX",
"phone": "",
"tarrif": "XXX",
"tariff_category": "NON-MD",
"service_band": "C ",
"status": "Active",
"status_period": "MAY",
"payment_status": null,
"arrears": "29431.78",
"long_x": "7.0385020000",
"lat_y": "5.4909420000",
"transactional_details": {
"queryresult": {
"responseMessage": "success",
"customer": {
"accountNumber": "XXXXXXXXXXX",
"meterNumber": "XXXXXXXXXXX",
"phoneNumber": "",
"lastName": "XXXXXXXXXXX",
"address": "XXXXXXXXXXX",
"city": "XXXXXXXXXXX",
"district": "Owerri",
"userCategory": "NON-MD",
"customerType": "metered",
"paymentPlan": "Prepaid",
"vat": 0,
"tariffCode": "R2SC-NMD",
"tariffRate": 52.6,
"arrearsBalance": 0,
"billedAmount": 0,
"billedDate": null,
"lastPayDate": "2021-09-21 12:16:46",
"lastpayment": {
"transactionRef": "88099064",
"units": 0,
"transactionDate": "JXXXXXXXXXXX",
"transactionId": "XXXXXXXXXXX",
"transactionBookId": 0,
"amountPaid": 1000,
"mscPaid": 0,
"invoiceNumber": "17289583"
}
},
"responseCode": 200,
"status": "true"
},
"status": true
}
}
],
"row_count": 2
}
}
I have various branches in this JSON response which i need to use. i generated a model class from this JSON as shown below
// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
public class Customer
{
public object district { get; set; }
public string feeder { get; set; }
public string feeder_code { get; set; }
public string transformer { get; set; }
public string dss_code { get; set; }
public string database_match { get; set; }
public string accountnumber { get; set; }
public string meterno { get; set; }
public string oldaccountnumber { get; set; }
public string odoo_account_number { get; set; }
public string customername { get; set; }
public string address { get; set; }
public string phone { get; set; }
public string tarrif { get; set; }
public string tariff_category { get; set; }
public string service_band { get; set; }
public string status { get; set; }
public string status_period { get; set; }
public object payment_status { get; set; }
public string arrears { get; set; }
public string long_x { get; set; }
public string lat_y { get; set; }
public TransactionalDetails transactional_details { get; set; }
}
public class Customer2
{
public string accountNumber { get; set; }
public string meterNumber { get; set; }
public string phoneNumber { get; set; }
public string lastName { get; set; }
public string address { get; set; }
public string city { get; set; }
public string district { get; set; }
public string userCategory { get; set; }
public string customerType { get; set; }
public string paymentPlan { get; set; }
public int vat { get; set; }
public string tariffCode { get; set; }
public double tariffRate { get; set; }
public int arrearsBalance { get; set; }
public int billedAmount { get; set; }
public object billedDate { get; set; }
public string lastPayDate { get; set; }
public Lastpayment lastpayment { get; set; }
}
public class Lastpayment
{
public string transactionRef { get; set; }
public int units { get; set; }
public string transactionDate { get; set; }
public string transactionId { get; set; }
public int transactionBookId { get; set; }
public int amountPaid { get; set; }
public int mscPaid { get; set; }
public string invoiceNumber { get; set; }
}
public class Queryresult
{
public string responseMessage { get; set; }
public Customer customer { get; set; }
public int responseCode { get; set; }
public string status { get; set; }
}
public class Result
{
public ObservableCollection<Customer> customers { get; set; }
public int row_count { get; set; }
}
public class Root
{
public bool error { get; set; }
public Result result { get; set; }
}
public class TransactionalDetails
{
public Queryresult queryresult { get; set; }
public bool status { get; set; }
}
Afterwards i used the C# code to deserialize the JSON as shown below
Root myroot = JsonConvert.DeserializeObject<Root>(readTask);
ObservableCollection<Customer> data = myroot.result.customers;
This works fine, however, i am stuck with just customer Data. I want to be able to get the Transactional details (Customer2) and Lastpayment branches in a collection view. how can i achieve this? Thanks

You can parse your json and read it by linq. ToObject method help you to convert nodes to specific class.
I have taken json text in InputJson variable and then paresed it.
var parsed = JObject.Parse(InputJson);
var innerNodes = JArray.Parse(parsed["result"]["customers"].ToString());
var CustomerList = innerNodes.Select(x => x.ToObject<Customer>()).ToList();
And if you need just some of properties you can use in this way
var CustomerList = innerNodes.Select(x =>
new Customer
{
district = x["district"],
feeder = x["feeder"].ToString(),
transactional_details =x["transactional_details"].ToObject<TransactionalDetails>()
})
.ToList();
If you have different nodes in your object , you can call nodes and check them not be null!
var CustomerList = innerNodes.Select(x => new
{
district = x["district"],
feeder = x["feeder"].ToString(),
transactional_details =x["transactional_details"]?.ToObject<TransactionalDetails>(),
Lastpayment = x["transactional_details"]?["queryresult"]?["customer"]?["lastpayment"]?.ToObject<Lastpayment>(),
billedAmount = x["transactional_details"]?["queryresult"]?["customer"]?["billedAmount"] ?.ToString()
}).ToList();

Customers is an array object so you must iterate through this array.
For example this would work:
Root myroot = JsonConvert.DeserializeObject<Root>(json);
myroot.result.customers.ToList().ForEach(c =>
{
Console.WriteLine(c.transactional_details.queryresult.customer.lastpayment.amountPaid);
});
Looking at Locals in vs debugger for
var customers = myroot.result.customers.ToList();
we get this:

fix Queryresult class by changing Customer to Customer2
public class Queryresult
{
public string responseMessage { get; set; }
public Customer2 customer { get; set; }
public int responseCode { get; set; }
public string status { get; set; }
}
now you can get a lastpayment
Root myroot = JsonConvert.DeserializeObject<Root>(readTask);
LastPayment lastPayment = myroot.result.customers
.Select(c=>c.transactional_details.queryresult.customer.lastpayment).FirstOrDefault();
how to use
var amountPaid = lastPayment.amountPaid; //1000
var invoiceNumber = lastPayment.invoiceNumber; //17289583

Related

Null value when mapping from Object.Property to Property with AutoMapper

I want to map Message to MessageDto, so in RoomRead response I will have Collection of MessageDto with Username == User.LastName
public class RoomReadDTO
{
public int Id { get; set; }
public string Name { get; set; }
public bool Type { get; set; }
public ICollection<MessageDTO> Messages { get; set; }
}
public class MessageDTO
{
public int Id { get; set; }
public string Username { get; set; }
public string Content { get; set; }
public DateTime Date { get; set; }
}
public class Message
{
public int Id { get; set; }
public string Content { get; set; }
public DateTime Date { get; set; }
public int UserId { get; set; }
public int RoomId { get; set; }
public User User { get; set; }
public Room Room { get; set; }
}
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Photo { get; set; }
public ICollection<Participants> Participations { get; set; } = new List<Participants>();
public ICollection<Message> Messages { get; set; } = new List<Message>();
}
With this AutoMapper configuration
CreateMap<Message, MessageDTO>()
.ForMember(dest => dest.Username, opt => opt.MapFrom(message => message.User.LastName));
But in response Username property is null
{
"id": 1,
"name": "Private Chat John",
"type": false,
"messages": [
{
"id": 1,
"username": null,
"content": "Hello!",
"date": "2022-12-25T10:30:50"
},
{
"id": 2,
"username": null,
"content": "Hi!",
"date": "2022-12-25T10:32:50"
}
]
}
Can anyone give me some advice?

Querying Json with Linq, Cannot access child value

I am new to C# with JSON. I would like to select with Nvidia API, the "featuredProduct" part, but I have an error
Cannot access child value on Newtonsoft.Json.Linq.JProperty.
This code works for the "searchedProducts" part.
Can you explain to me why?
const string url = "";
const int refresh = 3000;
string json = getGpuFromNvidia(url);
var jsonParse = JObject.Parse(json);
var result = jsonParse["searchedProducts"]["featuredProduct"]
.Where(n => n["isFounderEdition"].Value<bool>() == true)
.Select(p => new CarteGraphique
{
displayName = (string)p["displayName"],
prdStatus = (string)p["prdStatus"],
directPurchaseLink = (string)p["retailers"][0]["directPurchaseLink"]
})
.ToList();
I tested this code in VS
string json = ...your code
var jsonObj = JsonConvert.DeserializeObject<NvidiaRoot>(json);
var result = jsonObj.searchedProducts.productDetails
.Where(n => n.isFounderEdition)
.Select(p => new
{
displayName = p.displayName,
prdStatus = p.prdStatus,
directPurchaseLink = p.retailers[0].directPurchaseLink
})
.ToList();
OUTPUT
[
{
"displayName": "NVIDIA RTX 3090",
"prdStatus": "out_of_stock",
"directPurchaseLink": "https://www.ldlc.com/fiche/PB89455870.html"
},
{
"displayName": "NVIDIA RTX 3070",
"prdStatus": "out_of_stock",
"directPurchaseLink": "https://www.ldlc.com/fiche/PB74221588.html"
},
{
"displayName": "NVIDIA RTX 3060 Ti",
"prdStatus": "out_of_stock",
"directPurchaseLink": "https://www.ldlc.com/fiche/PB54012144.html"
},
{
"displayName": "NVIDIA RTX 3070 Ti",
"prdStatus": "out_of_stock",
"directPurchaseLink": null
},
{
"displayName": "NVIDIA RTX 3080 Ti",
"prdStatus": "out_of_stock",
"directPurchaseLink": null
}
]
UPDATE
if you need just a feature product
var featuredProduct = jsonObj.searchedProducts.featuredProduct;
var result = new
{
displayName = featuredProduct.displayName,
prdStatus = featuredProduct.prdStatus,
directPurchaseLink = featuredProduct.retailers[0].directPurchaseLink
};
Short OUTPUT
{
"displayName": "NVIDIA RTX 3080",
"prdStatus": "out_of_stock",
"directPurchaseLink": "https://www.ldlc.com/fiche/PB15921567.html"
}
Full OUTPUT
var result = jsonObj.searchedProducts.featuredProduct;
{
"displayName": "NVIDIA RTX 3080",
"totalCount": 1,
"productID": 30045,
"imageURL": "https://assets.nvidia.partners/images/png/nvidia-geforce-rtx-3080.png",
"productTitle": "NVIDIA GEFORCE RTX 3080",
"digitialRiverID": "",
"productSKU": "NVGFT080",
"productUPC": "NVGFT080_FR",
"productUPCOriginal": "NVGFT080",
"productPrice": "€719.00",
"productAvailable": false,
"productRating": null,
"customerReviewCount": null,
"isFounderEdition": true,
"isFeaturedProduct": true,
"certified": false,
"manufacturer": "NVIDIA",
"locale": "FR",
"isFeaturedProdcutFoundInSecondSearch": false,
"category": "GPU",
"gpu": "RTX 3080",
"purchaseOption": "",
"prdStatus": "out_of_stock",
"minShipDays": null,
"maxShipDays": null,
"shipInfo": null,
"isOffer": false,
"offerText": "",
"retailers": [
{
"productId": 30045,
"productTitle": "NVIDIA GEFORCE RTX 3080",
"logoUrl": "https://assets.nvidia.partners/logos/geforce/retailer-ldlc.png",
"isAvailable": true,
"salePrice": "719.00",
"directPurchaseLink": "https://www.ldlc.com/fiche/PB15921567.html",
"purchaseLink": "https://www.ldlc.com/fiche/PB15921567.html",
"hasOffer": false,
"offerText": null,
"partnerId": "45",
"storeId": "45",
"upc": "NVGFT080_FR",
"sku": "NVGFT080",
"stock": 0,
"retailerName": "https://www.ldlc.com",
"type": 80
}
],
"productInfo": [
{
"name": "cooling_system",
"value": "Fan"
},
{
"name": "gpu_boost_clock_speed",
"value": "1.71 GHz"
},
{
"name": "gpu_memory_size",
"value": "10 GB"
}
],
"compareProductInfo": [
{
"name": "cooling_system",
"value": "Fan"
},
{
"name": "gpu_clock_speed",
"value": "1.44 GHz"
},
{
"name": "gpu_boost_clock_speed",
"value": "1.71 GHz"
},
{
"name": "gpu_memory_size",
"value": "10 GB"
}
]
}
classes
public class NvidiaRoot
{
public object categories { get; set; }
public List<Filter> filters { get; set; }
public object filterGroups { get; set; }
public object search { get; set; }
public string version { get; set; }
public List<Sort> sort { get; set; }
public Pagination pagination { get; set; }
public SearchedProducts searchedProducts { get; set; }
public Disclaimer disclaimer { get; set; }
}
public class FilterValue
{
public string dispValue { get; set; }
public object dispValueDesription { get; set; }
public object groupType { get; set; }
public int units { get; set; }
public bool #checked { get; set; }
public object imageURL { get; set; }
public bool isValidate { get; set; }
}
public class Filter
{
public string displayName { get; set; }
public string filterField { get; set; }
public string displayMaxValues { get; set; }
public string fieldType { get; set; }
public int? selectedMinRangeVal { get; set; }
public int? selectedMaxRangeVal { get; set; }
public int? defaultMinRangeVal { get; set; }
public int? defaultMaxRangeVal { get; set; }
public string unitsOfMeasure { get; set; }
public bool #checked { get; set; }
public object units { get; set; }
public List<FilterValue> filterValues { get; set; }
public string dataType { get; set; }
public bool showCount { get; set; }
public int filterDisplayOrder { get; set; }
}
public class Sort
{
public string displayName { get; set; }
public string value { get; set; }
public bool selected { get; set; }
}
public class Pagination
{
public int page { get; set; }
public int limit { get; set; }
public int totalRecords { get; set; }
public bool featuredProductIncludedInCount { get; set; }
}
public class Retailer
{
public int productId { get; set; }
public string productTitle { get; set; }
public string logoUrl { get; set; }
public bool isAvailable { get; set; }
public string salePrice { get; set; }
public string directPurchaseLink { get; set; }
public string purchaseLink { get; set; }
public bool hasOffer { get; set; }
public object offerText { get; set; }
public string partnerId { get; set; }
public string storeId { get; set; }
public string upc { get; set; }
public string sku { get; set; }
public int stock { get; set; }
public string retailerName { get; set; }
public int type { get; set; }
}
public class ProductInfo
{
public string name { get; set; }
public string value { get; set; }
}
public class CompareProductInfo
{
public string name { get; set; }
public string value { get; set; }
}
public class FeaturedProduct
{
public string displayName { get; set; }
public int totalCount { get; set; }
public int productID { get; set; }
public string imageURL { get; set; }
public string productTitle { get; set; }
public string digitialRiverID { get; set; }
public string productSKU { get; set; }
public string productUPC { get; set; }
public string productUPCOriginal { get; set; }
public string productPrice { get; set; }
public bool productAvailable { get; set; }
public object productRating { get; set; }
public object customerReviewCount { get; set; }
public bool isFounderEdition { get; set; }
public bool isFeaturedProduct { get; set; }
public bool certified { get; set; }
public string manufacturer { get; set; }
public string locale { get; set; }
public bool isFeaturedProdcutFoundInSecondSearch { get; set; }
public string category { get; set; }
public string gpu { get; set; }
public string purchaseOption { get; set; }
public string prdStatus { get; set; }
public object minShipDays { get; set; }
public object maxShipDays { get; set; }
public object shipInfo { get; set; }
public bool isOffer { get; set; }
public string offerText { get; set; }
public List<Retailer> retailers { get; set; }
public List<ProductInfo> productInfo { get; set; }
public List<CompareProductInfo> compareProductInfo { get; set; }
}
public class ProductDetail
{
public string displayName { get; set; }
public int totalCount { get; set; }
public int productID { get; set; }
public string imageURL { get; set; }
public string productTitle { get; set; }
public string digitialRiverID { get; set; }
public string productSKU { get; set; }
public string productUPC { get; set; }
public string productUPCOriginal { get; set; }
public string productPrice { get; set; }
public bool productAvailable { get; set; }
public object productRating { get; set; }
public object customerReviewCount { get; set; }
public bool isFounderEdition { get; set; }
public bool isFeaturedProduct { get; set; }
public bool certified { get; set; }
public string manufacturer { get; set; }
public string locale { get; set; }
public bool isFeaturedProdcutFoundInSecondSearch { get; set; }
public string category { get; set; }
public string gpu { get; set; }
public string purchaseOption { get; set; }
public string prdStatus { get; set; }
public object minShipDays { get; set; }
public object maxShipDays { get; set; }
public object shipInfo { get; set; }
public bool isOffer { get; set; }
public string offerText { get; set; }
public List<Retailer> retailers { get; set; }
public List<ProductInfo> productInfo { get; set; }
public List<CompareProductInfo> compareProductInfo { get; set; }
}
public class SearchedProducts
{
public int totalProducts { get; set; }
public bool featuredProductIncludedInCount { get; set; }
public bool featuredProductsFlag { get; set; }
public FeaturedProduct featuredProduct { get; set; }
public List<ProductDetail> productDetails { get; set; }
public List<object> suggestedProductDetails { get; set; }
}
public class Disclaimer
{
public string text { get; set; }
}
You can try the below code.
To get the Featured Product. Sample Working code Here
var jsonParse = JObject.Parse(json);
var featuredProduct = jsonParse["searchedProducts"]["featuredProduct"];
var f = new CarteGraphique
{
displayName = featuredProduct["displayName"].ToString(),
prdStatus = featuredProduct["prdStatus"].ToString(),
directPurchaseLink = featuredProduct["retailers"][0]["directPurchaseLink"].ToString()
};
Console.WriteLine("Featured Product Details : " + f.displayName + ", " + f.prdStatus + ", " + f.directPurchaseLink);

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

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 '\'

Issues with deserializing Json in C#

I have some json like this:
{
"status": "OK",
"result": {
"#type": "address_result__201301",
"barcode": "1301013030001010212212333002003031013",
"bsp": "044",
"dpid": "99033785",
"postcode": "4895",
"state": "QLD",
"suburb": "COOKTOWN",
"city": null,
"country": "AUSTRALIA"
},
"search_date": "03-12-2014 15:31:03",
"search_parameters": {},
"time_taken": 636,
"transaction_id": "f8df8791-531e-4043-9093-9f35881f6bb9",
"root_transaction_id": "a1fa1426-b973-46ec-b61b-0fe5518033de"
}
Then I created some classes:
public class Address
{
public string status { get; set; }
public Result results { get; set; }
public string search_date { get; set; }
public SearchParameters search_parameters { get; set; }
public int time_taken { get; set; }
public string transaction_id { get; set; }
public string root_transaction_id { get; set; }
}
public class Result
{
public string #type { get; set; }
public string barcode { get; set; }
public string bsp { get; set; }
public string dpid { get; set; }
public string postcode { get; set; }
public string state { get; set; }
public string suburb { get; set; }
public string city { get; set; }
public string country { get; set; }
}
public class SearchParameters
{
}
Finally, I use these code to get Json data:
string result = "Above json";
JavaScriptSerializer json = new JavaScriptSerializer();
Address add = json.Deserialize<Address>(result);
I see that, add.status, add.search_date... etc have values, but add.results is null.
What is wrong with my code?
I think the issue is using #type as illegal identifier. Try using [DataMember(Name = "#type")] before public string #type { get; set; }. Add a [DataContract] before public class Address.
Hence, your final code will be,
[DataContract]
public class Result
{
[DataMember(Name = "#type")]
public string #type { get; set; }
public string barcode { get; set; }
public string bsp { get; set; }
public string dpid { get; set; }
public string postcode { get; set; }
public string state { get; set; }
public string suburb { get; set; }
public string city { get; set; }
public string country { get; set; }
}

Categories