I have this kind of Json I want to save:
"data": {
"importMannerTypeList": {
"importMannerTypeID": 5,
"importMannerTypeDesc": "a"
},
"authoritySourceList": [
{
"authoritySourceID": 1,
"authoritySourceDesc": "b"
}
],
"permitStatusList": {
"permitStatusID": 4,
"permitStatusDesc": "c"
}}
All of them set as Arrays, but because authoritySourceList is multi select and not 1 object it look like this. here is the class that Deserialize the json, importMannerTypeList and permitStatusList failed to get the data from JSON why?
public class ImportPlantSettingsResponse
{
public ImportPlantSettingsResponse()
{
ImportMannerTypeList = new List<ImportMannerType>();
AuthoritySourceList = new HashSet<AuthoritySource>();
PermitStatusList = new List<PermitStatusResponse>();
}
public virtual List<ImportMannerType> ImportMannerTypeList { get; set; }
public virtual ICollection<AuthoritySource> AuthoritySourceList { get; set; }
public virtual List<PermitStatusResponse> PermitStatusList { get; set; }
As Selim Yildiz said,ImportMannerTypeList and PermitStatusList are not lists.Here is a demo:
Model:
public class ImportPlantSettingsResponse
{
public ImportPlantSettingsResponse()
{
AuthoritySourceList = new HashSet<AuthoritySource>();
}
public virtual ImportMannerType ImportMannerTypeList { get; set; }
public virtual ICollection<AuthoritySource> AuthoritySourceList { get; set; }
public virtual PermitStatusResponse PermitStatusList { get; set; }
}
action:
public IActionResult TestImportPlantSettingsResponse([FromBody] ImportPlantSettingsResponse importPlantSettingsResponse) {
return Ok();
}
result:
Related
I want to parse the JSON on the bottom. Till now I always have the static key for the variables, but in this example, the keys are always changing. Here the "58e7a898dae4c" and "591ab00722c9f" could have any value and change constantly. How can I get the value of the elements of the set to be able to reach the PreviewName value?
{
"key": "gun",
"objects": [
{
"name": "AK47",
"sets": {
"58e7a898dae4c": {
"set_id": "58e75660719a9f513d807c3a",
"preview": {
"resource": {
"preview_name": "preview.040914"
}
}
},
"591ab00722c9f": {
"set_id": "58eba618719a9fa36f881403",
"preview": {
"resource": {
"preview_name": "preview.81a54c"
}
}
}
}
}
]
}
public class Object
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("sets")]
public Dictionary<string, Set> Sets { get; set; }
}
public class Set
{
[JsonProperty("set_id")]
public string SetId { get; set; }
[JsonProperty("preview")]
public Preview Preview { get; set; }
}
public class Preview
{
[JsonProperty("resource")]
public ResourcePreview Resource { get; set; }
}
public class ResourcePreview
{
[JsonProperty("preview_name")]
public string PreviewName { get; set; }
}
var root = JsonConvert.DeserializeObject<RootObject>(json);
string previewName1 = root.Objects[0].Sets["58e7a898dae4c"].Preview.Resource.PreviewName;
string previewName2 = root.Objects[0].Sets["591ab00722c9f"].Preview.Resource.PreviewName;
you don't need to deserialize, you can parse
var jsonParsed=JObject.Parse(json);
string[] previewNames= ((JArray)jsonParsed["objects"])
.Select(v => ((JObject)v["sets"]))
.Select(i=>i.Properties().Select(y=> y.Value["preview"]["resource"])).First()
.Select(i=> (string) ((JObject)i)["preview_name"]).ToArray();
result
preview.040914
preview.81a54c
Maybe what am i asking is totally dumb, but i cannot find any examples where several form fields are bind to one (complex) property of the model.
extract from my unit test
...
var formData = new MultipartFormDataContent(formDataBoundary)
{
{ new StringContent("0123456789"), "did" },
{ new StringContent("A"), "connectionStatus" },
{ new StringContent("Access Only 2432/160"), "descriptionOffer" },
{ new StringContent("ADSN4DSL"), "codeOffer" },
{ new StringContent("NORMAL"), "supportLevel" },
{ new StringContent("Entreprise TEST"), "finalCustomerDenomination" },
{ new StringContent("RUE"), "finalCustomerStreetCode" },
{ new StringContent("du Test"), "finalCustomerStreetName" },
{ new StringContent("45"), "finalCustomerStreetNumber" },
{ new StringContent("69389"), "finalCustomerCityCode" },
{ new StringContent("69009"), "finalCustomerCityPostalCode" },
{ new StringContent("Lyon 9e"), "finalCustomerCityName" },
{ new StringContent("TestCustomer"), "finalCustomerContactName" },
{ new StringContent("0987654321"), "finalCustomerContactPhoneNumber" },
{ new StringContent("TestOperator"), "operatorContactName" },
{ new StringContent("0512346789"), "operatorContactPhoneNumber" },
{ new StringContent("Un commentaire opérateur"), "operatorComment" },
{ new StringContent("Une note..."), "note" },
};
var response = await client
.PostAsync(CREATION_URL, formData)
.ConfigureAwait(false);
...
extract from my controller
[HttpPost]
public async Task<IActionResult> Post(
[FromForm] CreationOrderInput input)
{
...
extract from my input model
public sealed class CreationOrderInput
{
public FrenchPhoneNumber Did { get; set; }
public Address FinalCustomerAddress { get; set; }
...
}
public class Address
{
public virtual NonEmptyString? Designation { get; set; }
public virtual NonEmptyString StreetLabel { get; set; }
public virtual NonEmptyString? StreetCode { get; set; }
public virtual NonEmptyString? StreetNumber { get; set; }
public virtual NonEmptyString? Cluster { get; set; }
public virtual NonEmptyString? Building { get; set; }
public virtual NonEmptyString? Stair { get; set; }
public virtual NonEmptyString? Floor { get; set; }
public virtual NonEmptyString? Door { get; set; }
public virtual NonEmptyString? Logo { get; set; }
public virtual NonEmptyString? CityCode { get; set; }
public virtual NonEmptyString CityPostalCode { get; set; }
public virtual NonEmptyString CityName { get; set; }
}
Basically, i'm trying to make a address binder to bind finalCustomerXXX to several properties of Address, but IModelBinder.BindModelAsync seems rather obscure to me.
Any help would be appreciated.
Update
I've no control over the POST and the field names.
You seem to want to pass a complex object to the post method.
Since the fields of the class you provide are inconsistent with some of the field names provided in MultipartFormDataContent, I will simplify your class to make the code more clear.
Basically, i'm trying to make a address binder to bind
finalCustomerXXX to several properties of Address
If you want to bind the fields under the corresponding class in the form of finalCustomerXXX, you must first make sure that the content before XXX is the field name of the corresponding class, and they need to be separated by dots(.), or put XXX in square bracketswhich([]) like follow:
FinalCustomerAddress.XXX or FinalCustomerAddress[XXX]
Here FinalCustomerAddress is the field name of Address type in CreationOrderInput class, and XXX is the field name of Address class like CityCode.
The following is a complete case, please refer to it:
public sealed class CreationOrderInput
{
public string Name { get; set; }
public FrenchPhoneNumber Did { get; set; }
public Address FinalCustomerAddress { get; set; }
}
public class FrenchPhoneNumber
{
public string number { get; set; }
}
public class Address
{
public virtual NonEmptyString? CityCode { get; set; }
public virtual NonEmptyString CityPostalCode { get; set; }
public virtual NonEmptyString CityName { get; set; }
}
Test:
var formData = new MultipartFormDataContent(formDataBoundary)
{
{ new StringContent("Lisa"), "Name" },
{ new StringContent("0123456789"), "Did[number]" },
{ new StringContent("69389"), "FinalCustomerAddress[CityCode]" },
{ new StringContent("69009"), "FinalCustomerAddress[CityPostalCode]" },
{ new StringContent("Lyon 9e"), "FinalCustomerAddress[CityName]" },
//or
//{ new StringContent("0123456789"), "Did.number" },
//{ new StringContent("69389"), "FinalCustomerAddress.CityCode" },
//{ new StringContent("69009"), "FinalCustomerAddress.CityPostalCode" },
//{ new StringContent("Lyon 9e"), "FinalCustomerAddress.CityName" },
};
var response = await client
.PostAsync(CREATION_URL, formData)
.ConfigureAwait(false);
Here is the test result:
I'm trying to deserialize a json file in c# and print the values of each individual value by using the key, but for the json values that are a list, I'm unable to print the desired values.
Json file:
{
"prod": {
"vpc_name": "vpc-us-east-1-it-prod",
"subnets": {
"application": [ "subnet-1234", "subnet-1345" ],
"data": [ "subnet-64t3", "subnet-f321" ],
"edge": [ "subnet-1ff3", "subnet-134g" ]
}
},
"dev": {
"vpc_name": "vpc-us-east-1-it-dev",
"subnets": {
"application": [
{ "subnet_id": "subnet-2345tf", "az": "us-east-1a" },
{ "subnet_id": "subnet-143f1", "az": "us-east-1b" }
],
"data": [
{ "subnet_id": "subnet-134f", "az": "us-east-1b" },
{ "subnet_id": "subnet-1324", "az": "us-east-1a" }
],
"edge": [
{ "subnet_id": "subnet-123434", "az": "us-east-1a" },
{ "subnet_id": "subnet-123fg", "az": "us-east-1b" }
]
}
}
}
C# code
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
namespace JsonDeserializer
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
string jsonString = File.ReadAllText(#"C:/Users/Stephen.Carvalho/source\repos/JsonDeserializer/JsonDeserializer/vpc_stack.json");
Rootobject vpcs = JsonSerializer.Deserialize<Rootobject>(jsonString);
Console.WriteLine(vpcs.dev.vpc_name);
Console.WriteLine(vpcs.dev.subnets.application);
}
}
public class Rootobject
{
public Prod prod { get; set; }
public Dev dev { get; set; }
}
public class Prod
{
public string vpc_name { get; set; }
public Subnets subnets { get; set; }
}
public class Subnets
{
public string[] application { get; set; }
public string[] data { get; set; }
public string[] edge { get; set; }
}
public class Dev
{
public string vpc_name { get; set; }
public Subnets1 subnets { get; set; }
}
public class Subnets1
{
public Application[] application { get; set; }
public Datum[] data { get; set; }
public Edge[] edge { get; set; }
}
public class Application
{
public string subnet_id { get; set; }
public string az0885b3b66d { get; set; }
public string az { get; set; }
}
public class Datum
{
public string subnet_id { get; set; }
public string az { get; set; }
}
public class Edge
{
public string subnet_id { get; set; }
public string az { get; set; }
}
}
Output
Hello World!
vpc-us-east-1-it-dev
JsonDeserializer.Application[]
I want to print the list of application subnets with prod.subnets but instead of getting the values returned I'm getting JsonDeserializer.Application[] as the output
That is because vpcs.dev.subnets.application is an array of Application. You can print the array of application subnets by first getting the subnet_ids then converting that array to a string.
Reason you see JsonDeserializer.Application[] is because your printing the object itself.. when you do that, you get the name of the object type instead of the values inside of it.
Console.WriteLine(string.Join(", ", vpcs.dev.subnets.application.Select(x => x.subnet_id)));
The Select statment goes through each of the application and returns only the subnet_id. Whenever you have an array / list, you can use the select method to get specific items from the list or create new object with this as well.
Documentation on Select
That's happening since you're trying to print an array in an line, you can try doing something like this:
Array.ForEach(vpcs.dev.subnets.application, Console.WriteLine);
or parsing it to a list and printing it
vpcs.dev.subnets.application.ToList().ForEach(i => Console.WriteLine(i.ToString()));
or you can also try doing it in a foreach:
foreach(var item in vpcs.dev.subnets.application)
{
Console.WriteLine(item.ToString());
}
anyone know how to insert this json array into mongodb using insertmany() and C# ??
i cant find any good source for this problem
MongoCollectionBase.InsertMany expects an IEnumerable<TDocument>.
So you need to deserialize your data json element to TDocument[], (Datum) and then pass that array to InsertMany.
Based on the below json, which is different from your screenshot
{
"data": [
{
"pulsa_code": "alfamart100",
"pulsa_op": "Alfamart Voucher",
"pulsa_nominal": "Voucher Alfamart Rp 100.000",
"pulsa_price": 100000,
"pulsa_type": "voucher",
"masaaktif": "0",
"status": "active"
}
]
}
This should work
//...
public class Datum
{
public string pulsa_code { get; set; }
public string pulsa_op { get; set; }
public string pulsa_nominal { get; set; }
public double pulsa_price { get; set; }
public string pulsa_type { get; set; }
public string masaaktif { get; set; }
public string status { get; set; }
public double harga { get; set; }
}
public class PriceListPrepaidModel
{
public List<Datum> data { get; set; }
}
public class PriceList : BaseDatabase
{
//NOTE: The strongly typed IMongoCollection<T> must be the same type as the entities passed to InsertMany
private IMongoCollection<Datum> _pricelistCollection;
//private IMongoCollection<PriceListPrepaidModel> _pricelistCollection;
public PriceList(IServiceProvider serviceProvider)
{
_pricelistCollection = DB.GetCollection<PriceListPrepaidModel>("price_prepaid");
}
public ResponseModel<string> PriceListPrepaidTest(PriceListPrepaidRequest request)
{
var entityResult = new ResponseModel<string>();
try
{
Console.WriteLine(response.Content);
//Desirialize to your model class, not JObject
var model = JsonConvert.DeserializeObject<PriceListPrepaidModel>(message.AsString);
foreach (var item in model.data)
{
item.pulsa_price = (int)item.pulsa_price + 200;
}
//Insert the array of `Datum`
_pricelistCollection.InsertMany(model.data);
entityResult.Value = JsonConvert.SerializeObject(model.data);
entityResult.Status = true;
}
catch (Exception ex)
{
entityResult.Messages.Add(new ResponseMessageModel()
{
Type = ResponseMessageModel.MessageType.ERROR,
Title = "Error",
Message = ex.Message
});
}
return entityResult;
}
}
hotel_pricesURL = string_builder.ToString();
RootobjectOne robjectOne = JsonConvert.DeserializeObject<RootobjectOne>(hotel_pricesURL);
List<OneStar> one_star_list = new List<OneStar>();
var check = robjectOne.onestar;
foreach(var items in check)
{
}
Including RootobjectOne class:
public class RootobjectOne
{
[JsonProperty("OneStar")]
public OneStar onestar { get; set; }
[JsonProperty("TwoStar")]
public TwoStar twostar { get; set; }
[JsonProperty("ThreeStar")]
public ThreeStar threestar { get; set; }
[JsonProperty("FourStar")]
public FourStar fourstar { get; set; }
[JsonProperty("FiveStar")]
public FiveStar fivestar { get; set; }
public IEnumerator GetEnumerator()
{
return (IEnumerator)this;
}
}
public class OneStar
{
public IEnumerator GetEnumerator()
{
return (IEnumerator)this;
}
[JsonProperty("median")]
public string median { get; set; }
[JsonProperty("lowest")]
public string lowest { get; set; }
[JsonProperty("value")]
public string value { get; set; }
//public string
}
**this is the response from the web service**
{
"5 star": {
"median": "134.04",
"lowest": "83.57",
"value": "134.04"
},
"1 star": {
"median": "28.86",
"lowest": "28.86",
"value": "28.86"
},
"4 star": {
"median": "76.35",
"lowest": "36.71",
"value": "76.35"
},
"2 star": {
"median": "24.78",
"lowest": "20.42",
"value": "24.78"
},
"3 star": {
"median": "37.65",
"lowest": "20.33",
"value": "37.65"
}
}
I am getting an error stating
Unable to cast object of type 'OneStar' to type'System.Collections.IEnumerator'
Why? And how do I solve this?
First, your class is implementing, but not inheriting the IEnumerable interface, so it is still not seen as a collection.
Second, even if you inherit it, you have no collections in OneStar and nothing to enumerate.
Third, all those Json flags are not necessary as you are just redefining the defaults that are already set.
Solution
You need an additional "wrapper" class that is your collection, or just omit your custom implementation of an enumerable collection (as it does not appear from your code that you need it) and just define the property that contains the class as a collection:
public class RootobjectOne
{
public List<OneStar> onestar { get; set; }
public List<TwoStar> twostar { get; set; }
public List<ThreeStar> threestar { get; set; }
public List<FourStar> fourstar { get; set; }
public List<FiveStar> fivestar { get; set; }
}