public class News
{
public string author { get; set; }
public string title { get; set; }
public DateTime timestamp{ get; set; }
public string content { get; set; }
public bool forstudents { get; set; }
public List<link> links { get; set; }
public List<imgs> imgs { get; set; }
}
public class link
{
public string name { get; set; }
public string value { get; set; }
}
public class imgs
{
public string name { get; set; }
public string value { get; set; }
}
This is my Model Description then i connect to the Server
var _esServer = new ElasticSearchServer("http://localhost:9200");
var _esIndex = _esServer.GetIndex("campusoffice");
var news = _esIndex.Get<News>("/news", int.MaxValue);
and it should get everything right but
he doesnt map the name and the value in the list elements
{
"author": "soulseak",
"title": "Awsome",
"timestamp": 20130201,
"content": "Erster",
"forstudents": true,
"links": {
"myhome": "http://test.de"
},
"imgs": {
"myhome": "http://test.de"
}
}
the question is how to tell him what to put in name and value that myhome is in name and the url in value
You can do something like this:
public class User {
public User(string json) {
var jsonObject = Json.Decode(json);
MyName = (string)jsonObject.user.name;
MyTeamName = (string)jsonObject.user.teamname;
MyEmail = (string)jsonObject.user.email;
Players = (DynamicJsonArray) jsonObject.user.players;
}
public string MyName{ get; set; }
public string MyTeamName { get; set; }
public string MyEmail{ get; set; }
public Array Players { get; set; }
}
But would need to assign the values manually.
Example using your model (0 index based only, you would need to write a loop) but using a direct RestFul call:
var url = "http://localhost:9200/campusoffice/news";
var client = new WebClient();
var json = client.DownloadString(url);
var jsonObject = Json.Decode(json);
var links = (DynamicJsonArray) jsonObject.links;
var imgs = (DynamicJsonArray) jsonObject.imgs;
var news = new News
{ author = (string)jsonObject.author,
links = new List<link>() };
var aLink = new link { name = (string)links[0].myhome, value =
(string)imgs[0].myhome };
news.links.Add(aLink);
I typed this roughly without compiling/testing but should give you an idea.
Related
I am trying to consume an Api for c# project.
I have the request body sample as follows:
{
"tx_ref":"hooli-tx-1920bbtytty",
"amount":"100",
"currency":"NGN",
"redirect_url":"https://webhook.site/9d0b00ba-9a69-44fa-a43d-a82c33c36fdc",
"payment_options":"card",
"meta":{
"consumer_id":23,
"consumer_mac":"92a3-912ba-1192a"
},
"customer":{
"email":"user#gmail.com",
"phonenumber":"080****4528",
"name":"Yemi Desola"
},
"customizations":{
"title":"Pied Piper Payments",
"description":"Middleout isn't free. Pay the price",
"logo":"https://assets.piedpiper.com/logo.png"
}
}
I want to convert the code to C#, I did it as below, but the "meta", "customer", "customizations" are nested in the request, when I tried to reproduce the nested part of the code to c# I get an error.
Please how do I place my C# code to reflect the body with the nested part of the code?
var keyValues = new Dictionary<string, string>
{
{ "tx_ref", "N-872653uy09-9"},
{ "amount", "500"},
{ "currency","NGN"},
{ "redirect_url","mysite.com/ConcludeFunding.aspx"},
{ "payment_options","card"},
{ "meta"," "},
{ "customer"("email",EmailV) },
{ "customizations","mysite.com/Assets/Logo.jpg"},
};
//serialization using Newtonsoft JSON
string JsonBody = JsonConvert.SerializeObject(keyValues);
For this type of situation, I would create a root class. Then I would assign value to the class object and finally I would serialize the object using Newtonsoft JSON.
Code:
using Newtonsoft.Json;
using System;
namespace Solve
{
internal class Program
{
public class Meta
{
public int consumer_id { get; set; }
public string consumer_mac { get; set; }
}
public class Customer
{
public string email { get; set; }
public string phonenumber { get; set; }
public string name { get; set; }
}
public class Customizations
{
public string title { get; set; }
public string description { get; set; }
public string logo { get; set; }
}
public class Root
{
public string tx_ref { get; set; }
public string amount { get; set; }
public string currency { get; set; }
public string redirect_url { get; set; }
public string payment_options { get; set; }
public Meta meta { get; set; }
public Customer customer { get; set; }
public Customizations customizations { get; set; }
}
static void Main(string[] args)
{
var rootObj = new Root()
{
tx_ref = "N-872653uy09-9",
amount = "500",
currency = "NGN",
redirect_url = "mysite.com/ConcludeFunding.aspx",
payment_options = "card",
meta = new Meta()
{
consumer_id = 23,
consumer_mac = "92a3-912ba-1192a"
},
customizations = new Customizations()
{
title = "Pied Piper Payments",
description = "Middleout isn't free. Pay the price",
logo = "https://assets.piedpiper.com/logo.png"
},
customer = new Customer()
{
email = "user#gmail.com",
phonenumber = "080****4528",
name = "Yemi Desola"
}
};
string json = JsonConvert.SerializeObject(rootObj);
Console.WriteLine(json);
}
}
}
hello i've got some problems in c#(xamarin)
i followed XXX tutorials about pharsing..
I only need the Value.
Can someone tell me how i solve that problem?
my Json:
{
"Header":{
"Version":5,
"Device":"80",
"Timestamp":1610066048
},
"Data":{
"Inputs":[
{
"Number":2,
"AD":"A",
"Value":{
"Value":62.0,
"Unit":"1"
}
}
]
},
"Status":"OK",
"Status code":0
}
C#
var client = new WebClient();
string json = client.DownloadString("https://XXXXXXX.com/heizung.php");
Value1 news = JsonConvert.DeserializeObject<Value1>(json);
Ausgabe.Text = news.Value;
My Class
public class Header
{
public int Version { get; set; }
public string Device { get; set; }
public int Timestamp { get; set; }
}
public class Value1
{
public string Value { get; set; }
public string Unit { get; set; }
}
public class Input
{
public int Number { get; set; }
public string AD { get; set; }
public Value1 Value { get; set; }
}
public class Data
{
public List<Input> Inputs { get; set; }
}
public class Root
{
public Header Header { get; set; }
public Data Data { get; set; }
public string Status { get; set; }
public int Statuscode { get; set; }
}
Thanks, i hope y'all have a nice day.
Deserialize Root object and track value down:
Root news = JsonConvert.DeserializeObject<Root>(json);
Ausgabe.Text = news.Data.Inputs[0].Value.Value;
You should deserialize your json as a Root class:
var root = JsonConvert.DeserializeObject<Root>(json);
After the root object is deserialized you can select whatever value you need. E.g.:
var values = root.Data.Inputs.Select(i => i.Value.Value); // string sequence
I have two POCO types
PdfIndex and PieceEM:
public class PdfIndex
{
public string Path { get; set; }
public PieceEM Pdf { get; set; }
}
And PieceEM:
public class PieceEM
{
public string Id { get; set; }
public string Content { get; set; }
public string Language { get; set; }
public string Profession { get; set; }
public string DeparmentOfPiece { get; set; }
public string PieceType { get; set; }
public string PricingType { get; set; }
public string PieceId { get; set; }
public string Author { get; set; }
}
All pdfs read and but not indexed.
The code does not fail, just this address has no data
http://localhost:9200/fullegalpieces/_search?pretty=true
This is my index code:
public void IndexPiece(IEnumerable<PdfIndex> pdfIndexes)
{
foreach (var pdfIndex in pdfIndexes)
{
if (!File.Exists(pdfIndex.Path)) continue;
var pdfReader = new PdfReader(pdfIndex.Path);
string text = string.Empty;
for (int page = 1; page <= pdfReader.NumberOfPages; page++)
{
text += PdfTextExtractor.GetTextFromPage(pdfReader, page);
}
pdfReader.Close();
PieceEM _pdf = pdfIndex.Pdf;
_pdf.Content = IndexDocumentHelper.RemoveSpecialChar(text);
_pdf.Content += _pdf.Author;
_elasticClient.Index(_pdf, i => i
.Type<PieceEM>());
}
}
Path is correct.
This pdf exists locally,
and my post action is here:
[HttpPost]
public void IndexPiece(List<PdfIndex> pdfIndexes)
{
var elastic = new ElasticHelper.ElasticSearchHelper("http://localhost:9200/", "fullegalpieces");
elastic.IndexPiece(new List<PdfIndex> {
new PdfIndex
{
Path = #"C:\Users\Yılmaz\Desktop\özgeçmiş.pdf",
Pdf = new PieceEM
{
Id = "042f01f8-befc-40a7-9339-fa4fffe2c4e0",
PieceId = "bd7aaa9c-7c81-4675-a037-0fa56ad09003",
Language = "1",
PieceType ="2",
PricingType = "1",
Profession = "1",
Author = "ykaraagac",
DeparmentOfPiece = "1"
}
}
});
}
I have similar examples, but this does not work.
What can I do?
Thanks.
i checked my local log file and i saw this:
i indexed different POCO type, not PieceEM
I am consuming a REST API service. In the service response JSON, there are attribute names that include spaces and reserved words. I'm trying to map it to a C# class, but I can't assign attribute names that are the same as the field names.
Currently, the mapping only succeeds when the JSON attribute and C# class name of a field matches exactly, otherwise the value comes in as null.
Below is the JSON returned from the service:
{
"value": [ {
"accountNo": "JKBXXXXXXXXXVNX1",
"mainSalesPerson": "XXXXX",
"accountName": "XXXXXX",
"ledgerBalance": "-2,298.70",
"T+3": "0.00",
"T+4": "0.00",
"T+5 and Above": "2,298.70",
"riskRatedPortfolioValue": "109,057.50",
"exposure": "106,758.80",
"costToFirm": "",
"incomeToFirm": "14.59",
"costToIncome(%)": "",
"exposure(%)": "2.11",
"O/S Balance": "-2,298.70"
}],
"success": true
}
I have used the following mapping class:
public class CountObject
{
public string value { get; set; }
public string success { get; set; }
}
public class RiskManagementQueryValueObject
{
public string accountNo { get; set; }
public string mainSalesPerson { get; set; }
public string accountName { get; set; }
public string ledgerBalance { get; set; }
[SerializeAs(Name = "T+3")]
public string T3 { get; set; }
[SerializeAs(Name = "T+4")]
public string T4 { get; set; }
[SerializeAs(Name = "T+5 and Above")]
public string T5_and_Above { get; set; }
public string riskRatedPortfolioValue { get; set; }
public string exposure { get; set; }
public string costToFirm { get; set; }
public string incomeToFirm { get; set; }
[SerializeAs(Name = "costToIncome(%)")]
public string costToIncome { get; set; }
[SerializeAs(Name = "exposure(%)")]
public string exposure_per { get; set; }
[SerializeAs(Name = "O/S Balance")]
public string OS_Balance { get; set; }
}
public class RiskManagementQueryHeadertObject
{
public List<RiskManagementQueryValueObject> value { get; set; }
public bool success { get; set; }
}
And this how I talk to the service:
public List<RiskManagementQueryValueObject> getOverdues()
{
List<RiskManagementQueryValueObject> overdues = new List<RiskManagementQueryValueObject>();
var count = 0.0;
try
{
var restProxy = new RESTProxy();
var request = restProxy.initRestRequest("/cam/riskmanagement/1/query/count", Method.POST, new { requestCriteriaMap = new { currency = "LKR" } });
CountObject data = restProxy.Execute<CountObject>(request);
if (data.success.ToString().ToLower() != "true")
return null;
//get the page count
var pageCount = Math.Truncate(count / 300) + 1;
for (int j = 0; j < pageCount; j++)
{
var request2 = restProxy.initRestRequest(string.Format("/cam/riskmanagement/1/query/{0}", (j + 1).ToString()), Method.POST, new { requestCriteriaMap = new { currency = "LKR" } });
RiskManagementQueryHeadertObject data2 = restProxy.Execute<RiskManagementQueryHeadertObject>(request2);
overdues.AddRange(data2.value);
}
}
catch (Exception)
{
overdues = null;
}
return overdues;
}
public class RESTProxy
{
string DEFAULT_HOST = "http://xxx.xxx.xxx.xxx:xxx/";
string DEFAULT_MODULE = "xxx-rest";
string DEFAULT_USER = "xxx:xxx:xxx";
string DEFAULT_PASS = "xxx";
public T Execute<T>(RestRequest request) where T : new()
{
var client = new RestClient(string.Concat(DEFAULT_HOST, DEFAULT_MODULE))
{
Authenticator = new DigestAuthenticator(DEFAULT_USER, DEFAULT_PASS, DEFAULT_HOST)
};
var response = client.Execute<T>(request);
if (response.ErrorException != null)
{
throw response.ErrorException;
}
return response.Data;
}
public RestRequest initRestRequest(string pRestResourceName, Method pRestServiceVerb, object pRestRequestBody)
{
var request = new RestRequest(pRestResourceName, pRestServiceVerb);
request.RequestFormat = DataFormat.Json;
if (pRestRequestBody != null)
{
request.AddBody(pRestRequestBody);
}
return request;
}
}
How can I resolve this and serialize all the fields into my class definition?
Using the JsonProperty attribute worked for me:
Example:
This C# class:
public class Product
{
[JsonProperty(PropertyName = "Name/ + 1")]
public string Name { get; set; }
}
maps to the following javascript object:
var input = {"Name/ + 1": "PostName"};
I solved the issue. I added [DeserializeAs(Name ="")] instead of [SerializeAs(Name ="")]. I just did this in my C# Map class:
public class RiskManagementQueryValueObject
{
public string accountNo { get; set; }
public string mainSalesPerson { get; set; }
public string accountName { get; set; }
public string ledgerBalance { get; set; }
[DeserializeAs(Name = "T+3")]
public string T3 { get; set; }
[DeserializeAs(Name = "T+4")]
public string T4 { get; set; }
[DeserializeAs(Name = "T+5 and Above")]
public string T5_and_Above { get; set; }
public string riskRatedPortfolioValue { get; set; }
public string exposure { get; set; }
public string costToFirm { get; set; }
public string incomeToFirm { get; set; }
[DeserializeAs(Name = "costToIncome(%)")]
public string costToIncome { get; set; }
[DeserializeAs(Name = "exposure(%)")]
public string exposure_per { get; set; }
[DeserializeAs(Name = "O/S Balance")]
public string OS_Balance { get; set; }
}
I have json message
{"code":200,
"description":{
"15":{"id":"15","name":"US"},
"25":{"id":"25","name":"Canada"},
"msg":"Ok"}}
I am trying to deserialize it with such classes
public class NewCountry
{
public string id { get; set; }
public string name { get; set; }
}
public class NewCountryDescription
{
public List<NewCountry> Countries{ get; set; }
public string msg { get; set; }
}
public class RootObject
{
public int code { get; set; }
public NewCountryDescription description { get; set; }
}
var ListOfCountries = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(res);
But I am always getting null at NewCountry what i am doing wrong?
If you remove msg from your json or move it somewhere else (not in the descrition), it will work:
{"code":200,
"description":{
"15":{"id":"15","name":"US"},
"25":{"id":"25","name":"Canada"}
}}
public class RootObject
{
public int code { get; set; }
public Dictionary<string, NewCountry> description { get; set; }
}
public class NewCountry
{
public string id { get; set; }
public string name { get; set; }
}
You doesn't have parsable collection, so you can use JObject and dynamic or key/value access.
var result = JObject.Parse(res);
var description = (result["description"] as JObject);
if (description != null)
{
var root = new RootObject
{
code = (int)result["code"],
description = new NewCountryDescription
{
msg = description["msg"].ToString(),
Countries = (from prop in description.Properties()
where prop.Name != "msg"
select new NewCountry
{
id = prop.Value["id"].ToString(),
name = prop.Value["name"].ToString()
}).ToList()
}
};
Console.Write(root);
}