Suppose we have class Request which we want to serialize to json and deserialize from json.
class Request {
public string SessionId { get; set; }
...
public string InnerJson { get; set; }
}
As json it should looks like
{
"SessionId": 1,
...
"InnerJson": {
"some": "json object",
"whatever": 666
}
}
InnerJson is some json document (arbitrary type).
Is it good to use string for InnerJson in Request?
Is there any good way to design Request class?
If you are going for a strongly typed model I'd suggest a factory. For demonstration sake:
public abstract class AbstractOptions { }
public class Options1 : AbstractOptions { public int Whatever { get; set; } }
public class Options2 : AbstractOptions { public string Some { get; set; } }
public class Options3 : AbstractOptions {
[JsonProperty("when")] public DateTime When { get; set; }
[JsonProperty("inner")] public InnerComplexObject Inner { get; set; }
}
public class Request {
[JsonProperty("session-id")] public string SessionId { get; set; }
[JsonProperty("options")] public AbstractOptions Options { get; set; }
}
public class InnerComplexObject { }
then use it like:
var req1 = new Request() { SessionId = "s1", Options = new Options1 { Whatever = 123 } };
var req2 = new Request() { SessionId = "s2", Options = new Options2 { Some = "some" } };
var req3 = new JToken.Request() { SessionId = "s3", Options = new Options3 { When = DateTime.UtcNow, Inner = new InnerComplexObject() } };
Otherwise, for flexibility, keep InnerJson a string and use dynamic queries.
Related
I'm trying to serializa a json. I have created a helper class for it yet it claims that SerializeJsonBody has no definition of the fields I need to fill. When I use the deeper classes the definition is ok yet I won't create the full json.
My end result should look like this:
{"invoiceHash": { "hashSHA":{ "algorithm": "SHA-256","encoding": "Base64","value": {0}},"fileSize": {1}}, "invoicePayload":{ "type": "plain","invoiceBody": {2}} }
public class SerializeJsonBody
{
public invoiceHash invoiceHash { get; set; }
public invoicePayload invoicePayload { get; set; }
}
public class invoiceHash
{
public hashSHA hashSHA { get; set; }
public string fileSize { get; set; }
}
public class hashSHA
{
public string algorithm { get; set; }
public string encoding { get; set; }
public string value { get; set; }
}
public class invoicePayload
{
public string type { get; set; }
public string invoiceBody { get; set; }
}
SerializeJsonBody body = new SerializeJsonBody
{
algorithm = "SHA-256",
encoding = "Base64",
value = "",
fileSize = "",
type = "plain",
invoiceBody = ""
};
string json = JsonConvert.SerializeObject(body, Formatting.Indented);
Edit. I think I figured it out.. Not sure if the best way yest it works
SerializeJsonBody body = new SerializeJsonBody
{
invoiceHash = new invoiceHash
{
hashSHA = new hashSHA
{
algorithm = "SHA-256",
encoding = "Base64",
value = base64hash
},
fileSize = lenght
},
invoicePayload = new invoicePayload
{
type = "plain",
invoiceBody = base64
}
};
string json = JsonConvert.SerializeObject(body, Formatting.Indented);
There is no method with this signature in the documentation, I strongly recommend that you visit it
Your issue can be solved with JsonSerializerSettings
I am struggling to configure automaper for following scenario, where there is an extra level of indirection at the source level.
On DB layer we have structure:
ResultDB (hasa) List<CaseTriageResultDB> and CaseTriageResultDB has a TriageResultDB
On DTO layer we have structure:
ResultDTO (hasa) List<TriageResultDTO>
I want to configure automapper to map ResultDB objects to ResultDTO objects. Here is a (failing) test with dummy classes to demonstrate the problem:
public class TriageResultDB
{
public string Name { get; set; }
public string Description { get; set; }
}
public class CaseTriageResultDB
{
public TriageResultDB TriageResult { get; set; }
}
public class ResultDB
{
public double EstimatedCost { get; set; }
public IEnumerable<CaseTriageResultDB> CaseTriageResults { get; set; }
}
//-- DTOs (ResultDTO -> List<TriageResult>)
public class TriageResultDTO
{
public string Name { get; set; }
public string Description { get; set; }
}
public class ResultDTO
{
public double EstimatedCost { get; set; }
public IEnumerable<TriageResultDTO> TriageResults { get; set; }
}
[TestFixture]
public class MappingTests
{
MapperConfiguration CreateConfig()
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<TriageResultDB, TriageResultDTO>();
cfg.CreateMap<ResultDB, ResultDTO>();
});
return config;
}
[Test]
public void MapFromDBtoDTO()
{
var config = CreateConfig();
var resultDB = new ResultDB()
{
EstimatedCost = 100,
CaseTriageResults = new List<CaseTriageResultDB>()
{
new CaseTriageResultDB() { TriageResult = new TriageResultDB() { Name = "triageResult1", Description = "description1" }},
new CaseTriageResultDB() { TriageResult = new TriageResultDB() { Name = "triageResult2", Description = "description2" }}
}
};
var mapper = config.CreateMapper();
var dto = mapper.Map<ResultDTO>(resultDB);
Assert.AreEqual(100, dto.EstimatedCost);
Assert.AreEqual("triageResult1", dto.TriageResults.First().Name);
Assert.AreEqual("triageResult2", dto.TriageResults.Last().Name);
}
}
Worked it out myself, something like:
cfg.CreateMap<ResultDB, ResultDTO>()
.ForMember(dto => dto.TriageResults,
opt => opt.MapFrom(db => db.CaseTriageResults.Select(dbTriageResult => dbTriagResult.TriageResult)));
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;
}
}
I am retrieving the following JSON via a POST to an API
{
"State":"Andhra_Pradesh",
"District":"Guntur",
"Fact":"SELECT",
"Description":"",
"FactDate":"",
"FactNumber":"",
"FactType":"SELECT",
"Fact":{"Id":"1"}
}
I am able to execute the Ajax request via javascript, but I also want to consume the API through C# code.
I am using the below code, but I'm not quite sure on how to add the Fact object?
var values = new Dictionary<string, string>
{
{ "State", selectedState },
{ "District", selectedDistrict },
{ "Fact", ""},
{ "FactType", ""},
{ "FactNumber", ""},
{ "Description", ""},
{"Fact", "{Id,1}" },
{"FactDate", factDate.Date.ToString() }
};
using (var httpClient = new HttpClient())
{
var content = new FormUrlEncodedContent(values);
var response = await httpClient.PostAsync("http://api.in/" + "test", content);
}
How do I add the Fact object to Dictionary?
You'll probably need to define the data you are sending as actual class before using httpclient.
If you had only name value pairs then you could have used the NameValueCollection and sent as a formurlencoded but since you have a complex type, you might consider this below.
See below.
public class Rootobject
{
public string State { get; set; }
public string District { get; set; }
public Fact Fact { get; set; }
public string Description { get; set; }
public string CaseDate { get; set; }
public string FactNumber { get; set; }
public string FactType { get; set; }
}
public class Fact
{
public string Id { get; set; }
}
Usage is as below. be sure to include a reference to System.Net.Http.Formatting.dll
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var model = new Rootobject { State = "Andhra_Pradesh", District = "Guntur", FactType = "SELECT", Description = "", CaseDate = "", FactNumber = "", Fact = new Fact { Id = "1"} };
var data = await client.PostAsJsonAsync("http://api.in/" + "test", model);
I think this is just a json object, you can either create a class which have the same properties of (state, district etc ..) and use json serializer
or you can create JObject using Json.Net
You can use Newtonsonft.Json to to the serializaton/deserialization job and the code will be like that.
public class Rootobject
{
[JsonProperty("State")]
public string State { get; set; }
[JsonProperty("District")]
public string District { get; set; }
[JsonProperty("Fact")]
public Fact Fact { get; set; }
[JsonProperty("Description")]
public string Description { get; set; }
[JsonProperty("CaseDate")]
public string CaseDate { get; set; }
[JsonProperty("FactNumber")]
public string FactNumber { get; set; }
[JsonProperty("FactType")]
public string FactType { get; set; }
}
public class Fact
{
[JsonProperty("Id")]
public string Id { get; set; }
}
And then, after instatiating your object, just serialize it.
Rootobject example = new Rootobject();
//Add values to the variable example.
var objectSerialized = JsonConvert.SerializeObject(example);
After that, you will have a json ready to be send wherever you want.
Just change {"Fact", "{Id,1}" } to {"Fact.Id", "1" },
I'm using Newwtonsoft.JSON for build my json file, actually what I did is create different classes models, as this:
class GeneralModel
{
public string Language { get; set; }
}
and then for build the json file:
GeneralModel lsModel = new GeneralModel();
string json = JsonConvert.SerializeObject(lsModel);
File.WriteAllText(settingsFilePath, json);
this will create a json that contains Language, but I need to put in this json different classes, what I need is set an index that contains each class name, for example:
"GeneralModel": {
"Language" : "english"
},
"AnoherClassName": {
"ClassProperty" : value
}
how can I do this with Newtonsoft?
public class GeneralModel
{
public string Language { get; set; }
}
public class AnotherModel
{
public string AnotherProperty { get; set; }
}
public class SuperClass
{
public GeneralModel generalModel { get; set; }
public AnotherModel anotherModel { get; set; }
}
then
SuperClass s = new WMITest.SuperClass();
s.generalModel = new GeneralModel();
s.generalModel.Language = "language";
s.anotherModel = new AnotherModel();
s.anotherModel.AnotherProperty = "example";
string json = JsonConvert.SerializeObject(s);