Sending 2 Lists In A Class From Postman - c#

these are my classes.
public class BasketClass
{
public int HowMany { get; set; }
public int MBasketId { get; set; }
public int MVendorId { get; set; }
public int WInvestorId { get; set; }
public int MProductId { get; set; }
}
public class VendorPay
{
public int id { get; set; }
public int MVendorId { get; set; }
public bool IsCargoIncluded { get; set; }
public decimal CargoAmount { get; set; }
public decimal TotalAmount { get; set; }
}
public class PayBasketInputClass
{
public List<BasketClass> mOrderList { get; set; }
public List<VendorPay> vendorPayList { get; set; }
}
And this is my method.
public IActionResult PayBasket(int WInvestorId, PayBasketInputClass payInput, string paymenttype)
I gotta send payInput from body. But it includes two lists and its to complicated for me. Can you help me how to do it with an example?
Cheers.

{
"mOrderList": [
{
"HowMany": 1,
"MBasketId": 2,
"MVendorId": 3,
"WInvestorId": 4,
"MProductId": 5
}
],
"vendorPayList": [
{
"id": 1,
"MVendorId": 2,
"IsCargoIncluded": true,
"CargoAmount": 3.99,
"TotalAmount": 4.99
}
]
}
Json object is above is your PayBasketInputClass object in json structure.

Related

Deserialize a GSON generated JSON string n C#

I have a JSON generated through java using GSON. I want to recreate the same fields in C#. The JSON looks something like this.
{
"bool1": true,
"long1": 0,
"double1": 500.0,
"int1": 1,
"double2": 0.4,
"double3": 0.3,
"double4": 1.0,
"double5": 0.1,
"int2": 0,
"int3": 0,
"long2": 20160901,
"class1object1": {
"serialVersionUID": 1,
"class1int1": 0,
"class1int2": 0,
"class1int3": 0,
"class1double1": 68.3,
"class1doubleArray1": [68.3],
"class1double2": 65.45,
"class1doubleArray2": [65.45],
"class1int4": 1
},
"class1object2": {
"serialVersionUID": 1,
"class1int1": 135,
"class1int2": 138,
"class1int3": 105,
"class1double1": 68.1,
"class1doubleArray1": [67.57, 67.6, 67.48, 67.45, 67.39, 67.42, 67.38, 67.37, 67.35, 67.35, 67.37, 67.35, 67.36, 67.37, 67.35, 67.37, 67.38],
"class1double2": 67.26,
"class1doubleArray2": [67.5, 67.53, 67.46, 67.4, 67.39, 67.38, 67.37, 67.32, 67.33, 67.33, 67.33, 67.35, 67.36, 67.33, 67.33, 67.37, 67.34],
"class1int4": 240
},
"int4": 1,
"class2object1": {
"serialVersionUID": 1,
"class2double1": 2.8499999999999943,
"class2double2": 1.6758422688703467,
"class2double3": 0.09523809523809523
},
}
The definitions for all these classes and other fields are already there in my C# application. Also if required, the names of fields can be kept the same as they are in the JSON.
Can someone please help me with what tool should I use in order to achieve this and how? Also there is a possibility of NaN/Inf values as well (Secondary problem, not very important and can be omitted from JSON if required.
You can use JSON2CSHARP or copy json to clipboard > go to Visual Studio > Edit>Paste Special>Paste JSON as Classes. It's give you model classes. Uisng Newtonsoft.Json package you can deserialize your json:
JsonConvert.DeserializeObject<RootClassName>("json");
Your model class should look:
public class Class1
{
public int serialVersionUID { get; set; }
public int class1int1 { get; set; }
public int class1int2 { get; set; }
public int class1int3 { get; set; }
public double class1double1 { get; set; }
public List<double> class1doubleArray1 { get; set; }
public double class1double2 { get; set; }
public List<double> class1doubleArray2 { get; set; }
public int class1int4 { get; set; }
}
public class Class2
{
public int serialVersionUID { get; set; }
public int class1int1 { get; set; }
public int class1int2 { get; set; }
public int class1int3 { get; set; }
public double class1double1 { get; set; }
public List<double> class1doubleArray1 { get; set; }
public double class1double2 { get; set; }
public List<double> class1doubleArray2 { get; set; }
public int class1int4 { get; set; }
}
public class Class3
{
public int serialVersionUID { get; set; }
public double class2double1 { get; set; }
public double class2double2 { get; set; }
public double class2double3 { get; set; }
}
public class RootObject
{
public bool bool1 { get; set; }
public int long1 { get; set; }
public double double1 { get; set; }
public int int1 { get; set; }
public double double2 { get; set; }
public double double3 { get; set; }
public double double4 { get; set; }
public double double5 { get; set; }
public int int2 { get; set; }
public int int3 { get; set; }
public int long2 { get; set; }
public Class1 Class1 { get; set; }
public Class2 Class2 { get; set; }
public int int4 { get; set; }
public Class3 Class3 { get; set; }
}
Also if you want use others name in C# classes you need use JsonProperty(PropertyName = "yourJsonName"),this allows you to specify a different name this example should help:
public class Foo
{
[JsonProperty(PropertyName = "fooJSONname")]
public int FooNumber { get; set; }
}

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

C# : extract/retrieve child node from JSON structure

How can we extract or retrieve child nodes values from JSON structure in C#.
my app is using OpenWeatherMap, I need to retrieve name from city, temp from list and description from weather nodes, my JSON and Class structure are below
{
"cod": "200",
"message": 0.0284,
"city": {
"id": 2643743,
"name": "London",
"coord": {
"lon": -0.12574,
"lat": 51.50853
},
"country": "GB",
"population": 0,
"sys": {
"population": 0
}
},
"cnt": 1,
"list": [
{
"dt": 1429268400,
"temp": {
"day": 12.21,
"min": 4.86,
"max": 13.18,
"night": 4.86,
"eve": 11.76,
"morn": 12.21
},
"pressure": 1028.8,
"humidity": 66,
"weather": [
{
"id": 803,
"main": "Clouds",
"description": "broken clouds",
"icon": "04d"
}
],
"speed": 5.9,
"deg": 67,
"clouds": 80
}
]
}
C# Class
public class WeatherForeCast
{
public string City { get; set; }
public decimal Day { get; set; }
public decimal Min { get; set; }
public decimal Max { get; set; }
public decimal Night { get; set; }
public string Description { get; set; }
}
Till date I'm familiar with using JSON.net for serialize and deserialize C# objects to JSON which has exact same structure.
If you just want to populate an instance of WeatherForecast, you could use a few SelectToken calls on a plain JObject:
var parsed = JObject.Parse(json);
var forecast = new WeatherForeCast();
forecast.City = parsed.SelectToken("city.name").Value<string>();
forecast.Day = parsed.SelectToken("list[0].temp.day").Value<decimal>();
forecast.Description = parsed.SelectToken("list[0].weather[0].description").Value<string>();
forecast.Min = parsed.SelectToken("list[0].temp.min").Value<decimal>();
forecast.Max = parsed.SelectToken("list[0].temp.max").Value<decimal>();
forecast.Night = parsed.SelectToken("list[0].temp.night").Value<decimal>();
Note that this is pretty brittle though, it's making assumptions about the contents of the JSON. If the JSON changes, the path to various properties in SelectToken will be incorrect and this code will throw an exception.
Use json2csharp.com to generate your classes.
public class Coord
{
public double lon { get; set; }
public double lat { get; set; }
}
public class Sys
{
public int population { get; set; }
}
public class City
{
public int id { get; set; }
public string name { get; set; }
public Coord coord { get; set; }
public string country { get; set; }
public int population { get; set; }
public Sys sys { get; set; }
}
public class Temp
{
public double day { get; set; }
public double min { get; set; }
public double max { get; set; }
public double night { get; set; }
public double eve { get; set; }
public double morn { get; set; }
}
public class Weather
{
public int id { get; set; }
public string main { get; set; }
public string description { get; set; }
public string icon { get; set; }
}
public class List
{
public int dt { get; set; }
public Temp temp { get; set; }
public double pressure { get; set; }
public int humidity { get; set; }
public List<Weather> weather { get; set; }
public double speed { get; set; }
public int deg { get; set; }
public int clouds { get; set; }
}
public class RootObject
{
public string cod { get; set; }
public double message { get; set; }
public City city { get; set; }
public int cnt { get; set; }
public List<List> list { get; set; }
}
Then use JSON.NET to deserialize into the class structure and extract the properties you want.
var jsonObject = JsonConvert.DeserializeObject<RootObject>(jsonString);
You now have an instance of RootObject and you can traverse it as needed to extract the specific value(s) you need.

json DeserializeObject in c# using json.net

Im having a problem deserializing some json I get from a webserver and I think it is beacuse of the formating.
The json look like this :
{
"post_count": {
"total_posts": 1,
"sfw_total_posts": 1,
"use": 0
},
"posts_per_page": 1,
"posts": [
{
"guid": 10019127,
"wp_id": 656197,
"type": "media",
"title": "Test",
"path": "TestPath",
"publish_start": 1385559021,
"author": "Test",
"web_url": "http://www.test.com",
"nsfw": "No",
"modified": 1385532803,
"video": "No",
"likes": 484,
"dislikes": 51,
"main_category_id": 71,
"thumbnails": [
{
"w": 120,
"h": 120
},
{
"w": 240,
"h": 240
}
],
"comments": 26
}
],
"server": "100.200",
"time": 0.42163896560669
}
I have created a class with the value for there that I want to use and then using
LatestChive lastchives = JsonConvert.DeserializeObject<LatestChive>(jsonstring);
I try to deserialize it but all the values return null (I only want the stuff that is in "posts")
If I try with "post_count" or "posts_per_page" i can get the values just not from the the "posts"
I hope this makes sense and there is a easy fix thank you.
Define your classes as
public class PostCount
{
public int total_posts { get; set; }
public int sfw_total_posts { get; set; }
public int use { get; set; }
}
public class Thumbnail
{
public int w { get; set; }
public int h { get; set; }
}
public class Post
{
public int guid { get; set; }
public int wp_id { get; set; }
public string type { get; set; }
public string title { get; set; }
public string path { get; set; }
public int publish_start { get; set; }
public string author { get; set; }
public string web_url { get; set; }
public string nsfw { get; set; }
public int modified { get; set; }
public string video { get; set; }
public int likes { get; set; }
public int dislikes { get; set; }
public int main_category_id { get; set; }
public List<Thumbnail> thumbnails { get; set; }
public int comments { get; set; }
}
public class LatestChive
{
public PostCount post_count { get; set; }
public int posts_per_page { get; set; }
public List<Post> posts { get; set; }
public string server { get; set; }
public double time { get; set; }
}
For your future work see http://json2csharp.com/

Convert json into class

I need to create clasess from json, but found some strange part that really troubles me. This is example from documentation that i have to response to them. There is some "Fenway Room" that should be variable but it looks it is value (room name) that contain other properties.
{
"api_version" : 4 ,
"hotel_ids" : [97497],
"num_hotels" : 1,
"hotels" :
[
{
"hotel_id": 97497,
"room_types":
{
"Fenway Room":
{
"url": "",
"price": 178,
"fees": 80,
"fees_at_checkout": 0,
"taxes": 20,
"taxes_at_checkout": 0,
"final_price": 278
}
}
}
]
}
here are classes online generated, and looks wrong. it looks that is not possible.
public class FenwayRoom
{
public string url { get; set; }
public int price { get; set; }
public int fees { get; set; }
public int fees_at_checkout { get; set; }
public int taxes { get; set; }
public int taxes_at_checkout { get; set; }
public int final_price { get; set; }
}
public class RoomTypes
{
public FenwayRoom __invalid_name__Fenway Room { get; set; }
}
public class Hotel
{
public int hotel_id { get; set; }
public RoomTypes room_types { get; set; }
}
public class RootObject
{
public int api_version { get; set; }
public List<int> hotel_ids { get; set; }
public int num_hotels { get; set; }
public List<Hotel> hotels { get; set; }
}
This is my first working with json, so im really confused. Json looks valid, but it is possible to create classes from that or i should create response manualy?... joining strings...
added example:
"hotels" :[
{
"hotel_id" : 258705 ,
"room_types" :
{
"Room 1" :
{
"url" :"", "price" : 1136 , "fees" : 101.55 , "taxes" : 50.00 , "final_price" : 1287.55 ,
}
"Room 2" :
{
"url" :"", "price" : 1136 , "fees" : 101.55 , "taxes" : 50.00 , "final_price" : 1287.55 ,
}
}
}
]
Where "Room 1" and "Room 2" are room titles, not properties or variables... it can be anything here.
This works with ASP.NET MVC4. I don't know if lower supports it.
public JsonResult MyAPI()
{
return Json(new RootObject { api_version = 1,
hotel_ids = 12342,
hotels = new Hotel{ hotel_id = 123,
room_types = new RoomTypes...
}
}
}
As far as Json is an object herited from the class Controller.
You can generate classes from json by creating a new class, copying the json out, go to Edit->paste special->paste json as classes
Then you will get this:
class Class1
{
public class Rootobject
{
public int api_version { get; set; }
public int[] hotel_ids { get; set; }
public int num_hotels { get; set; }
public Hotel[] hotels { get; set; }
}
public class Hotel
{
public int hotel_id { get; set; }
public Room_Types room_types { get; set; }
}
public class Room_Types
{
public FenwayRoom FenwayRoom { get; set; }
}
public class FenwayRoom
{
public string url { get; set; }
public int price { get; set; }
public int fees { get; set; }
public int fees_at_checkout { get; set; }
public int taxes { get; set; }
public int taxes_at_checkout { get; set; }
public int final_price { get; set; }
}
}
try this one out
http://json2csharp.com/
http://json2csharp.com/
Paste your Json String there it will generate the Json Class

Categories