How to declare dynamic key using class?
{
"balls": {"a8bf081d-eaef-44db-ba25-97ed8c0b30ef": {"team": {"runs": 1,
"extras": 0,
"ball_count": 1,
"wicket": 0
}
},
}}
Based on your last Json format, still not valid but close.
You have the following class
public class Team
{
public int runs { get; set; }
public int extras { get; set; }
public int ball_count { get; set; }
public int wicket { get; set; }
}
Using a Dictionary<string, Team> you can simply:
var objFoo = new
{
balls = new Dictionary<string, Team>
{
{
"a8bf081d-eaef-44db-ba25-97ed8c0b30ef",
new Team{
runs=1,
extras=0,
ball_count=1,
wicket=0
}
}
}
};
var result = JsonConvert.SerializeObject(objFoo);
online Exemple
Related
I have an object which has a property which is list. Based on that list I want to filter property of it along with other properties of an object.
I have following object
{
Adult: 1,
Child: 0,
Infant: 0,
Origin: 'ABC',
Destination: 'XYZ',
DomesticFlightInfos: [{
FlightID: flightId1,
FareID: fareId1,
IsInbound: true
},
{
FlightID: flightId2,
FareID: fareId2,
IsInbound: false
}
]
};
I want following two objects
{
Adult: 1,
Child: 0,
Infant: 0,
Origin: 'ABC',
Destination: 'XYZ',
DomesticFlightInfos: [{
FlightID: flightId1,
FareID: fareId1,
IsInbound: true
}]
};
Adult: 1,
Child: 0,
Infant: 0,
Origin: 'ABC',
Destination: 'XYZ',
DomesticFlightInfos: [{
FlightID: flightId2,
FareID: fareId2,
IsInbound: false
}]
I was trying to do reservation.DomesticFlightInfos.Where(x => !x.IsInbound); which was wrong and got casting issue. What could be the best solution for it?
C# Object
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
new DomesticFlightReservation()
{
Adult = 1,
Child = 0,
Infant = 0,
Origin = "ABC",
Destination = "XYZ",
DomesticFlightInfos = new List<DomesticFlightInfo>(){
new DomesticFlightInfo{
FlightID= "flightId1",
FareID= "fareId1",
IsInbound= true
},
new DomesticFlightInfo {
FlightID= "flightId2",
FareID= "fareId2",
IsInbound= false
}
}
};
}
}
public class DomesticFlightReservation
{
public int Adult { get; set; } = 0;
public int Child { get; set; } = 0;
public int Infant { get; set; } = 0;
public string Origin { get; set; }
public string Destination { get; set; }
public List<DomesticFlightInfo> DomesticFlightInfos { get; set; }
}
public class DomesticFlightInfo
{
public string FlightID { get; set; }
public string FareID { get; set; }
// True for inbound, false for outbound
public bool IsInbound { get; set; }
}
Since you haven't provided C# object, assuming your C# objects to be defined as
public class DomesticFlightInfo
{
public string FlightID { get; set; }
public string FareID { get; set; }
public bool IsInbound { get; set; }
}
public class RootObject
{
public int Adult { get; set; }
public int Child { get; set; }
public int Infant { get; set; }
public string Origin { get; set; }
public string Destination { get; set; }
public List<DomesticFlightInfo> DomesticFlightInfos { get; set; }
}
If your intention is to separate the Inbounds and Outbound flights to separate groups, you could
var reservation = JsonConvert.DeserializeObject<RootObject>(str);
var flattenedReservation = new[]{reservation}.SelectMany(x=>x.DomesticFlightInfos
.GroupBy(v=>v.IsInbound)
.Select(c =>
{
x.DomesticFlightInfos = c.ToList();
return x;
}));
var jsonCollection = flattenedReservation.Select(x=> JsonConvert.SerializeObject(x,settings));
If your intention is to separate out each flight info into separate jsons, you could
var flattenedReservation = new[]{reservation}.SelectMany(x=>x.DomesticFlightInfos
.Select(c =>
{
x.DomesticFlightInfos = new List<DomesticFlightInfo>{c};
return x;
}));
var jsonCollection = flattenedReservation.Select(x=> JsonConvert.SerializeObject(x));
Output
If you have a list as a collection, you can use SelectMany
So, if you have a list
List<RootObject> rootObjects
then you can do this like flatten the list to get individual items:
rootObjects.SelectMany(x=> x.DomesticFlightInfos).Where(y => !y.IsInbound);
I use AutoMapper 8.1.0 in a asp.net core project. I have an Automapper mapping that doesn't work as I expected. I reproduced the configuration so you can test it by yourself. So I have an ExpenseReport with a collection of ExpenseReportItem and this one with another collection. I have to keep the data of eTaxCollection after the mapping, but they are lost in the process.
So the question is why values of eTaxCollections are lost after calling _mapper.Map(vmodel, model) and how can I keep them?
The ignore attribute don't work. I also tried UseDestinationValue(). I lost 2 days trying to figure it out and I'm exhausted.
public void WeatherForecasts()
{
int[] excludeTaxes = new int[] { 2 };
var vmodel = new ExpenseReportCreateEditModel();
vmodel.Expenses.Add(new ExpenseReportItemModel()
{
ExcludeTaxIds = excludeTaxes,
Total = 12,
Id = 1
});
// fetch from bd
var model = new ExpenseReport();
// values will be lost after _mapper.Map...
var eTaxCollections = new HashSet<ExcludeExpenseReportItemTax>();
eTaxCollections.Add(new ExcludeExpenseReportItemTax()
{
TaxId = 1,
ExpenseReportItemId = 1
});
model.Items.Add(new ExpenseReportItem()
{
ExcludeTaxes = eTaxCollections,
ExpenseReportId = 1,
Id = 9
});
_mapper.Map(vmodel, model);
}
public class ExpenseReportCreateEditModelProfile : Profile
{
public ExpenseReportCreateEditModelProfile()
{
CreateMap<ExpenseReportCreateEditModel, ExpenseReport>()
.ForMember(d => d.Items, s => s.MapFrom(m => m.Expenses));
}
}
public class ExpenseReportItemModelProfile : Profile
{
public ExpenseReportItemModelProfile()
{
CreateMap<ExpenseReportItemModel, ExpenseReportItem>()
.ForMember(d => d.ExcludeTaxes, s => s.Ignore()); // <<<==== data are lost
}
}
public class ExpenseReportCreateEditModel
{
public int Id { get; set; }
public ICollection<ExpenseReportItemModel> Expenses { get; set; }
public ExpenseReportCreateEditModel()
{
Expenses = new HashSet<ExpenseReportItemModel>();
}
}
public class ExpenseReportItemModel
{
public int Id { get; set; }
public ICollection<int> ExcludeTaxIds { get; set; }
public decimal Total { get; set; }
public ExpenseReportItemModel()
{
ExcludeTaxIds = new HashSet<int>();
}
}
public class ExpenseReport
{
public int Id { get; set; }
public virtual ICollection<ExpenseReportItem> Items { get; set; }
public ExpenseReport()
{
Items = new HashSet<ExpenseReportItem>();
}
}
public class ExpenseReportItem
{
public int Id { get; set; }
public int ExpenseReportId { get; set; }
public virtual ICollection<ExcludeExpenseReportItemTax> ExcludeTaxes { get; set; }
public ExpenseReportItem()
{
ExcludeTaxes = new HashSet<ExcludeExpenseReportItemTax>();
}
}
public class ExcludeExpenseReportItemTax
{
public int ExpenseReportItemId { get; set; }
public virtual ExpenseReportItem ExpenseReportItem { get; set; }
public int TaxId { get; set; }
}
Thank you for any help
Edit
I execute the execution plan and perhaps this is the problem:
$typeMapDestination = ($dest ?? .New WebApplication1.Controllers.SampleDataController+ExpenseReportItem());
This is only way I can lost the values.
I have to find a solution now
Here the complete execution plan :
.If ($src == null) {
.Default(WebApplication1.Controllers.SampleDataController+ExpenseReportItem)
} .Else {
.Block() {
$typeMapDestination = ($dest ?? .New WebApplication1.Controllers.SampleDataController+ExpenseReportItem());
.Try {
.Block(System.Int32 $resolvedValue) {
.Block() {
$resolvedValue = .If (
$src == null || False
) {
.Default(System.Int32)
} .Else {
$src.Id
};
$typeMapDestination.Id = $resolvedValue
}
}
} .Catch (System.Exception $ex) {
.Block() {
.Throw .New AutoMapper.AutoMapperMappingException(
"Error mapping types.",
$ex,
.Constant<AutoMapper.TypePair>(AutoMapper.TypePair),
.Constant<AutoMapper.TypeMap>(AutoMapper.TypeMap),
.Constant<AutoMapper.PropertyMap>(AutoMapper.PropertyMap));
.Default(System.Int32)
}
};
$typeMapDestination
}
}
I want to send Post Request with C# WebClient with this Json Schema :
[
{
"id": "00000000-0000-0000-0000-000000000000",
"points": [
{
"timestamp": "2017-12-04T16:07:44.562Z",
"value": 0
}
]
}
]
I've tried This :
public class RequestData
{
public string id {get; set; }
public points points { get; set; }
}
public class points
{
public DateTime timestamp { get; set; }
public float value { get; set; }
}
My Program :
Random number = new Random();
var req = new RequestData();
req.id = "0e13d9c-571c-44f4-b796-7c40c0e20a1d";
req.points = new points { timestamp = DateTime.UtcNow, value =
number.Next(100, 99999) };
JsonSerializerSettings settings = new JsonSerializerSettings();
var data = JsonConvert.SerializeObject(req);
WebClient client = new WebClient();
client.Headers.Add(HttpRequestHeader.Authorization,
AquaAtuhorization.accessToken);
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
client.UploadString ("http://localhost:8080/api/v1/data/writeNumericValues",
data );
And I always get Http 415 (Unsupported Media Type).
How could I format my C# Object as the restApi accepeted Format.
Look at the JSON, the square brackets [ ] denote that something is an array. In this case both RequestData and points have to be an array, see the example below:
public class RequestData
{
public string id { get; set; }
public List<points> points { get; set; } // I use list, could be an array
}
public class points
{
public DateTime timestamp { get; set; }
public float value { get; set; }
}
Then construct your req object like this:
var req = new List<RequestData> // Again I use list, could be an array
{
new RequestData
{
id = "0e740d9c-571c-44f4-b796-7c40c0e20a1d",
points = new List<points> // Defined as a list, even though it has one entry
{
new points
{
timestamp = DateTime.UtcNow,
value = number.Next(100, 99999)
}
}
}
};
Then just serialize it as normal, the result will be the below:
[
{
"id":"0e740d9c-571c-44f4-b796-7c40c0e20a1d",
"points":[
{
"timestamp":"2017-12-04T17:12:25.8957648Z",
"value":59522.0
}
]
}
]
Your Json class needs to be like this, see http://json2csharp.com/ or use paste as JSON from VS https://blog.codeinside.eu/2014/09/08/Visual-Studio-2013-Paste-Special-JSON-And-Xml/
public class Point
{
public DateTime timestamp { get; set; }
public int value { get; set; }
}
public class RootObject
{
public string id { get; set; }
public List<Point> points { get; set; }
}`
I am trying to build a function where a user can upload a json file.
Each row in the json file can have a different nr of properties(i.e. columns).
5 of these properties are always the same so I want those to be deserialized to an object. The rest of the properties have to go into a dictionary or something.
Here is a json example:
[{
"Projekt": "Bakker Bouw Service",
"Ruimte": "Hoofdgebouw",
"Apparaat": {
"project": "Bosboom001",
"versie": "812"
},
"Apparaat naam": "",
"Status": "Goedgekeurd",
"Testname1": "",
"Testname3": "2000-01-04T10:37:00+01:00",
"Testname7": "2001-01-03T00:00:00+01:00"
}, {
"Projekt": "Bakker Bouw Service",
"Ruimte": "Hoofdgebouw",
"Apparaat": {
"project": "Vlaams003",
"versie": "713"
},
"Apparaat naam": "",
"Status": "Goedgekeurd",
"Testname1": "Slecht",
"Testname7": "2000-01-04T10:37:00+01:00",
"Testname9": "2001-01-03T00:00:00+01:00",
"Testname16": "18MOhm",
"Testname23": "OK"
}, {
"Projekt": "Bakker Bouw Service",
"Ruimte": "Hoofdgebouw",
"Apparaat": {
"project": "Vlaams017",
"versie": "73"
},
"Apparaat naam": "GDR34Z5",
"Status": "Afgekeurd",
"Testname7": "2000-01-04T10:37:00+01:00",
"Testname10": "0,012mA",
"Testname16": "200MOhm",
"Testname23": "200MOhm",
"Testname25": "Afgekeurd",
"Testname31": "0,01mA"
}
]
Here is the class to deserialze to:
public class KeuringRegel
{
public string Projekt { get; set; }
public string Ruimte { get; set; }
public Apparaat Apparaat { get; set; }
[JsonProperty(PropertyName = "Apparaat naam")]
public string Apparaatnaam { get; set; }
public string Status { get; set; }
public Dictionary<string, object> testNames { get; set; }
}
public class Apparaat
{
public string project { get; set; }
public string versie { get; set; }
}
And here is the controller
public IActionResult Upload(IFormFile file)
{
string fileContent = null;
using (var reader = new StreamReader(file.OpenReadStream()))
{
fileContent = reader.ReadToEnd();
}
List<KeuringRegel> keuringRegelList = JsonConvert.DeserializeObject<List<KeuringRegel>>(fileContent);
//More stuff here
}
The json successfully deserializes but the testNames value is always null. I understand why, because there is no testNames property in the Json file. However, how do I achieve what I want? I am no Json expert.
One way you can do this, assuming that there is only testNameNNNN entries as supplemental values, is to use the JsonExtensionDataAttribute like this:
public class KeuringRegel
{
public string Projekt { get; set; }
public string Ruimte { get; set; }
public Apparaat Apparaat { get; set; }
[JsonProperty(PropertyName = "Apparaat naam")]
public string Apparaatnaam { get; set; }
public string Status { get; set; }
[JsonExtensionData()]
public Dictionary<string, object> testNames { get; set; }
}
This will give you the values whos don't fall into one of the other properties:
It's a bit of a "blunt instrument" but you could always perform some post-processing on the returned instances of KeuringRegel to remove any errant entries from testNames (i.e. things that don't match the pattern testNameNNNN).
If your JSON does contain things that don't match the pattern testNameNNNN which would therefore get included, you could implement a custom class for the testNames property:
public class KeuringRegel
{
public string Projekt { get; set; }
public string Ruimte { get; set; }
public Apparaat Apparaat { get; set; }
[JsonProperty(PropertyName = "Apparaat naam")]
public string Apparaatnaam { get; set; }
public string Status { get; set; }
[JsonExtensionData()]
public TestNames testNames { get; set; }
}
public class TestNames : Dictionary<string, object>
{
public new void Add(string key, object value)
{
if (key.StartsWith("testname", StringComparison.OrdinalIgnoreCase))
{
base.Add(key, value);
}
}
}
This will check each item that is added to the testNames dictionary and prevent its addition if (as in my comment where I had an item in the JSON of "badgerBadgetCatCat": 3) it doesn't match the pattern.
Here u are full example
internal class Program
{
private static void Main(string[] args)
{
var str = #"[{
""Projekt"": ""Bakker Bouw Service"",
""Ruimte"": ""Hoofdgebouw"",
""Apparaat"": {
""project"": ""Bosboom001"",
""versie"": ""812""
},
""Apparaat naam"": """",
""Status"": ""Goedgekeurd"",
""Testname1"": """",
""Testname3"": ""2000-01-04T10:37:00+01:00"",
""Testname7"": ""2001-01-03T00:00:00+01:00""
}, {
""Projekt"": ""Bakker Bouw Service"",
""Ruimte"": ""Hoofdgebouw"",
""Apparaat"": {
""project"": ""Vlaams003"",
""versie"": ""713""
},
""Apparaat naam"": """",
""Status"": ""Goedgekeurd"",
""Testname1"": ""Slecht"",
""Testname7"": ""2000-01-04T10:37:00+01:00"",
""Testname9"": ""2001-01-03T00:00:00+01:00"",
""Testname16"": ""18MOhm"",
""Testname23"": ""OK""
}, {
""Projekt"": ""Bakker Bouw Service"",
""Ruimte"": ""Hoofdgebouw"",
""Apparaat"": {
""project"": ""Vlaams017"",
""versie"": ""73""
},
""Apparaat naam"": ""GDR34Z5"",
""Status"": ""Afgekeurd"",
""Testname7"": ""2000-01-04T10:37:00+01:00"",
""Testname10"": ""0,012mA"",
""Testname16"": ""200MOhm"",
""Testname23"": ""200MOhm"",
""Testname25"": ""Afgekeurd"",
""Testname31"": ""0,01mA""
}
]";
var sw = Stopwatch.StartNew();
var result = Mapper.Map(str);
sw.Stop();
Console.WriteLine($"Deserialized at {sw.ElapsedMilliseconds} ms ({sw.ElapsedTicks} tiks)");
}
public static class Mapper
{
static Mapper()
{
List<string> names = new List<string>();
IEnumerable<PropertyInfo> p = typeof(KeuringRegel).GetProperties().Where(c => c.CanRead && c.CanWrite);
foreach (var propertyInfo in p)
{
var attr = propertyInfo.GetCustomAttribute<JsonPropertyAttribute>();
names.Add(attr != null ? attr.PropertyName : propertyInfo.Name);
}
Properties = names.ToArray();
}
private static string[] Properties { get; }
public static KeuringRegel[] Map(string str)
{
var keuringRegels = JsonConvert.DeserializeObject<KeuringRegel[]>(str);
var objs = JsonConvert.DeserializeObject(str) as IEnumerable;
var objectList = new List<JObject>();
foreach (JObject obj in objs)
objectList.Add(obj);
for (var i = 0; i < keuringRegels.Length; i++)
{
keuringRegels[i].testNames = new Dictionary<string, object>();
foreach (var p in objectList[i].Children().OfType<JProperty>().Where(c => !Properties.Contains(c.Name)).ToArray())
keuringRegels[i].testNames.Add(p.Name, p.Value);
}
return keuringRegels;
}
}
public class KeuringRegel
{
public string Projekt { get; set; }
public string Ruimte { get; set; }
public Apparaat Apparaat { get; set; }
[JsonProperty(PropertyName = "Apparaat naam")]
public string Apparaatnaam { get; set; }
public string Status { get; set; }
public Dictionary<string, object> testNames { get; set; }
}
public class Apparaat
{
public string project { get; set; }
public string versie { get; set; }
}
}
Below codes run perfectly but i want to re generate simply
static void YeniMethodListele()
{
Calısan calisan = new Calısan(){ ID=1, Ad="xxx", SoyAd="yyy"};
List<Calısan> myList = new List<Calısan>();
myList.Add(calisan);
MyCalısan myCalısan = new MyCalısan() { list = myList };
//myCalısan.list.Add(calisan);
foreach (Calısan item in myCalısan.list)
{
Console.WriteLine(item.Ad.ToString());
}
}
}
public class Calısan
{
public int ID { get; set; }
public string Ad { get; set; }
public string SoyAd { get; set; }
}
public class MyCalısan
{
public List<Calısan> list { get; set; }
public MyCalısan()
{
list = new List<Calısan>();
}
}
Here is a sample of a couple of ways to create the list a little more simply. Note the small change to the Calısan object to give it a default constructor and an overloaded constructor.
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
////Calısan calisan = new Calısan() { ID = 1, Ad = "xxx", SoyAd = "yyy" };
MyCalısan myCalısan = new MyCalısan();
//option 1:
//==========
myCalısan.list.AddRange(new[] { new Calısan() { ID = 1, Ad = "xxx", SoyAd = "yyyy" }, new Calısan() { ID = 2, Ad = "blah", SoyAd = "jiggy" } });
//option 2:
//=========
myCalısan.list.AddRange(new[] { new Calısan(1, "xxx", "yyy"), new Calısan(2, "blah", "jiggy") });
////myCalısan.list.Add(calisan);
foreach (Calısan item in myCalısan.list)
{
Console.WriteLine(item.Ad.ToString());
}
Console.ReadKey();
}
}
public class Calısan
{
public Calısan() { }
public Calısan(int id, string ad, string soyad)
{
ID = id;
Ad = ad;
SoyAd = soyad;
}
public int ID { get; set; }
public string Ad { get; set; }
public string SoyAd { get; set; }
}
public class MyCalısan
{
public List<Calısan> list { get; set; }
public MyCalısan()
{
list = new List<Calısan>();
}
}
}