I would like to ask how do I get the data using the JSON. I am using the Web API and deploy using request and response.
Class1.cs
This is calling the web API by using the request and response.
public static string Test()
{
string strReq = "{ \"header\": { \"Token\": \"ba42d11f - e0ae - 4d6c - 800a - 1564485b7ccb\"},\"body\": { \"SOHeaders\": [{ \"WarehouseCode\": \"W001\", \"CompanyCode\": \"C001\", \"SONo\": \"SO001\"}]}}";
UploadToBCSSoftSCM a = new UploadToBCSSoftSCM();
string strRes = a.GetSOSts(strReq);
return strRes;
}
HomeController.cs
I can get the response from here but I don't know how to split or parse the data.
public ActionResult Index()
{
// ViewBag.Title = "Home Page";
string r = Class1.Test();
Debug.WriteLine(r);
return View();
}
The result of response is
{
"header": {
"Token": "7c6cbeba-ff57-40d2-8759-84ccb59235fd",
"DtTime": "2020-02-20 13:10:34.365",
"ResultCode": "S",
"ResultMsg": ""
},
"body": [
{
"WarehouseCode": "W001",
"CompanyCode": "C001",
"SONo": "SO001",
"SOSts": "New"
}
]
}
O site json2csharp.com you can generate classes necessary to deserialize JSON.
public class Header
{
public string Token { get; set; }
public string DtTime { get; set; }
public string ResultCode { get; set; }
public string ResultMsg { get; set; }
}
public class Body
{
public string WarehouseCode { get; set; }
public string CompanyCode { get; set; }
public string SONo { get; set; }
public string SOSts { get; set; }
}
public class RootObject
{
public Header header { get; set; }
public List<Body> body { get; set; }
}
Then using JSON.NET you can deserialize your response into objects.
var data = JsonConvert.DeserializeObject<RootObject>(json);
and then in loop you can reach all records
foreach(var d in data.body)
{
}
Related
I am calling a Solr Apache search url and it turns Json data format. However, when I parse the Json, I receive null data. My Json format is like below:
responseHeader:
status: 0
QTime: 1
params:
q: "mykeyword"
response:
numFound: 67
start: 0
docs:
0:
tstamp: "xxxxx.xxxx.xxxx"
digest: "xxxxxxxxxxxxxxx"
boost: 0.010186654
id: "https://myserer/faq.html"
title: "xxxx"
url: "xxxxxx"
_version_:"xxxxxx"
content: "xxxxxxxxxx"
1:
tstamp: "xxxx"
.....
so I created dataModel to map the json data format:
public class ResponseModel
{
public ResponseHeader responseheader { get; set; }
public Response_ responsedata { get; set; }
}
public class Response_
{
public int numFound { get; set; }
public int start { get; set; }
public Doc doc { get; set; }
}
public class Params
{
public string q { get; set; }
}
public class Page
{
public string tstamp { get; set; }
public string digest { get; set; }
public string boost { get; set; }
public string id { get; set; }
public string title { get; set; }
public string url { get; set; }
public string _version_ { get; set; }
public string content { get; set; }
}
public class Doc
{
public List<Page> pages { get; set; }
}
my code to retrieve json search results:
string baseURL = "http://myserver:8983/solr/nutch/select?q=" + keyword;
string responseBody = string.Empty;
keyword = Request.Form["txtSearchTerm"];
if (!string.IsNullOrEmpty(keyword))
{
responseBody = getJSONString(baseURL);
}
var myData = JsonConvert.DeserializeObject<ResponseModel>(responseBody);
var Response = myData.responsedata.doc; //The Response is null here
// ...
private static string getJSONString(string apiURL)
{
// it returns json string
}
Where is the problem? BTW, there are a lot of \n line break in the json data. Is that the problem and how to deal with it? Thanks
add json data sample below:
{
"responseHeader": {
"status": 0,
"QTime": 0,
"params": {
"q": "Intranet"
}
},
"response": {
"numFound": 19,
"start": 0,
"docs": [
{
"tstamp": "2020-05-20T01:23:56.427Z",
"digest": "d615d21052125d3023a6ea5a244a6be0",
"boost": 0.043801095,
"id": "https://myserver/services/index.html",
"title": "Office of Services",
"url": "https://myserver/services/index.html",
"content": "Office of Services\nWelcome to the xxxx Website\nAccessibility Navigation:\nSkip to the header\nSkip to the main content\nSkip to the footer\nIt appears that you are viewing this site with an outdated browser.\nUpdate your browser for the best viewing experience by downloading the latest version below:\nInternet Explorer\nGoogle Chrome\nFirefox\nSafari\nMenu\nSearch\nSearch\n ...\nTop\n",
"_version_": 1667170768636608512
},
{
"tstamp": "2020-05-20T01:23:56.426Z",
"digest": "16cc4c01acd01d15ddbc59b7d43b435f",
"boost": 0.045213405,
"id": "https://myserver/media/index.html",
"title": "Library Technical",
"url": "https://myserver/media/index.html",
"content": "Library Technical Services Website\nAccessibility Navigation:\nSkip to the header\nSkip to the main content\nSkip to the footer\nIt appears that you are viewing this site with an outdated browser.\nUpdate your browser for the best viewing experience by downloading the latest version below:\nInternet Explorer\nGoogle Chrome\nFirefox\nSafari\nMenu\nSearch\nSearch\n ... INTRANET\Top\n",
"_version_": 1667170768619831298
}
]
}
}
The problem is that you have an object in your json namely response and in your c# classes, you have created the property named responseData which won't map because they differ in the name, Either you would have to set the JsonProperty name to response or you should entirely change the name of your property to response. Besides, there is a web application that will correctly parse your json and will generate the C# classes for you relevantly. Here is the code that I have generated for you for the response you have shared:
public partial class WebRequestResult
{
[JsonProperty("responseHeader")]
public ResponseHeader ResponseHeader { get; set; }
[JsonProperty("response")]
public Response Response { get; set; }
}
public class Response
{
[JsonProperty("numFound")]
public long NumFound { get; set; }
[JsonProperty("start")]
public long Start { get; set; }
[JsonProperty("docs")]
public List<Doc> Docs { get; set; }
}
public class Doc
{
[JsonProperty("tstamp")]
public DateTimeOffset Tstamp { get; set; }
[JsonProperty("digest")]
public string Digest { get; set; }
[JsonProperty("boost")]
public double Boost { get; set; }
[JsonProperty("id")]
public Uri Id { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("url")]
public Uri Url { get; set; }
[JsonProperty("content")]
public string Content { get; set; }
[JsonProperty("_version_")]
public double Version { get; set; }
}
public class ResponseHeader
{
[JsonProperty("status")]
public long Status { get; set; }
[JsonProperty("QTime")]
public long QTime { get; set; }
[JsonProperty("params")]
public Params Params { get; set; }
}
public class Params
{
[JsonProperty("q")]
public string Q { get; set; }
}
And you should parse your json data to C# like this:
var myData = JsonConvert.DeserializeObject<WebRequestResult>(responseBody);
You can generate your C# classes from app.quicktype.io
I have A Json file Which can be used for deserialize to Entity framework. For simplify we can assume the Json like this
{
"stat": "val0",
"results": [
{
"datasets": [
"val1",
"val2"
],
"head": "val3"
},
{
"datasets": [
"val4",
"val5"
],
"head": "val6"
}
]
}
And my Entity Classes like
[Serializable]
public class Root
{
[Key]
public int Id { get; set; }
public int stat { get; set; }
public List<Result> results { get; set; }
}
[Serializable]
public class Result
{
[Key]
public int Id { get; set; }
public List<String> _strings { get; set; }
public List<string> Strings
{
get { return _strings; }
set { _strings = value; }
}
[Required]
public string datasets
{
get { return String.Join(",", _strings); }
set { _strings = value.Split(',').ToList(); }
}
public string head{ get; set; }
public virtual root { get; set; }
}
I know Entity Framework does not support primitive types and I know problem causes from my datasets fields. that I found this way to solve String array deserialize issue here. I have tried
URL = "http://...";//Restful webservice address
WebClient client = new WebClient();
String JSON= client.DownloadString(URL);
var dsobj = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<RootObject>(json);
But I got
System.InvalidOperationException
Then I have decided to use Newtonsoft
URL = "http://...";//Restful webservice address
WebClient client = new WebClient();
String JSON= client.DownloadString(URL);
var dsobj = JsonConvert.DeserializeObject<Root>(json);
Then I got this error
Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: [. Path 'results[0].senses[0].definition', line 1, position...
I found this but I cant figure it out.
How can Fix these isseus. Any help appreciated.
Your json consist of two unwanted commas, try removing those
try
[Serializable]
public class Root
{
[Key]
public int Id { get; set; }
public string stat { get; set; } // changed to a string
public List<Result> results { get; set; }
}
[Serializable]
public class Result
{
[Key]
public int Id { get; set; }
public List<String> _dataSets { get; set; }
public List<string> dataSets // the JSON array will deserialize into this property
{
get { return _dataSets; }
set { _dataSets = value; }
}
[Required]
public string DatasetsAsString
{
get { return String.Join(",", _dataSets); }
set { _dataSets = value.Split(',').ToList(); }
}
public string head{ get; set; }
public virtual root { get; set; }
}
Edit: stat property has to be a string too.
I have the following json and I am trying to deserialize to insert it into a SQL table, I have tried to use JsonConvert and JObject without positive result
Json
{
"id": "123123",
"publisherId": "Empresa",
"notificationType": "Orden",
"headers": {
"providerId": "ABC123"
},
"content": {
"id": "987987",
"orderId": "4444444",
"apiName": "Services",
"method": "GetOrder",
"verb": "GET",
"urlMethod": "https://api.com"
},
"contentVersion": "1.0"
}
Model
public class Headers
{
public string providerId { get; set; }
}
public class Content
{
public string id { get; set; }
public string orderId { get; set; }
public string apiName { get; set; }
public string method { get; set; }
public string verb { get; set; }
public string urlMethod { get; set; }
}
public class RootModel
{
public string id { get; set; }
public string publisherId { get; set; }
public string notificationType { get; set; }
public Headers headers { get; set; }
public Content content { get; set; }
public string contentVersion { get; set; }
}
Code
public static List<Models.RootModel> getJson()
{
using (StreamReader r = new StreamReader("c:\\LOG\\20180528\\201805281039.json"))
{
string json = r.ReadToEnd();
return JsonConvert.DeserializeObject<Models.RootModel>(json);
}
}
You are giving me the following error
Error CS0029 No se puede convertir implícitamente el tipo 'WebApplication1.Models.RootModel' en 'System.Collections.Generic.List'
I really do not know if I'm on the right track, is it necessary to deserialize to insert in the DB, or is there another way?
Thanks in advance for the help
Just as the error states, it can not implicitly convert an instance of your model to a collection of your model.
You're trying to return a single instance:
return JsonConvert.DeserializeObject<Models.RootModel>(json);
But your method is expecting to return a list of instances:
public static List<Models.RootModel> getJson()
If you're just returning one instance (since the JSON represents an object, not an array of objects), change your method to reflect that:
public static Models.RootModel getJson()
change your code
public static Models.RootModel getJson()
{
using (StreamReader r = new StreamReader("c:\\LOG\\20180528\\201805281039.json"))
{
string json = r.ReadToEnd();
return JsonConvert.DeserializeObject<Models.RootModel>(json);
}
}
I started to learn C# and some Json, I am trying to get this form of Json format:
Desired Output :
I have tried this:
static void Main(string[] args)
{
var myjason = new myJson
{
ContentDisposition = "",
md5 = "da855ff838250f45d528a5a05692f14e",
file_name = "MyFile.docx",
features = new[] { "te" },
te = new te { reports = new[] { "pdf", "xml" } },
// images = new img { { a.id = "7e6fe36e-889e-4c25-8704-56378f0830df", a.revision = 1 }, { a.id = "e50e99f3-5963-4573-af9e-e3f4750b55e2", a.revision = 1 } }
};
string json = JsonConvert.SerializeObject(myjason, Formatting.Indented);
Console.WriteLine(json);
}
public class myJson
{
public string ContentDisposition{ get; set; }
public string md5 { get; set; }
public string file_name { get; set; }
public string[] features { get; set; }
public te te { get; set; }
public img images { get; set; }
}
public class a
{
public string id { get; set; }
public int revision { get; set; }
}
public class te
{
public string[] reports { get; set; }
}
public class img
{
public a[] images { get; set; }
}
And here is my current output:
Current output:
Please help, thanks a lot!
I think you are a bit confused about what's going on here. It looks like you're trying to POST some JSON to some endpoint.
Content-Disposition and Content-Type are HTTP headers. They are not JSON.
The JSON starts with the first { and this is the body of the POST. To create that body, you could use a C# object like:
public class MyJson {
public class MyRequest request {get ;set;}
}
public class MyRequest {
public string md5 {get;set;}
public string file_name {get;set;}
public string file_type {get;set;}
public List<string> features {get;set;}
public MyTe te {get;set;}
}
public class MyTe {
public List<string> reports {get;set;}
public List<MyImages> images {get;set;}
}
public class MyImages {
public string id {get;set;}
public int revision {get;set;}
}
And then use JsonConvert.SerializeObject on a MyJson object. To set the HTTP headers depends on what you're trying to do and with which tools, and that probably belongs in a different question.
EDIT: I said "and so on" because it's really just a rote exercise, and there are better tools to do this but I've updated.
Content-Disposition and Content-Type are request headers so they don't need to be in your json body
Here I've also demostrated how you can set a custom json property name using JsonProperty attribute.
static void Main(string[] args)
{
var myjason = new myJsonClass
{
Request = new requestClass
{
md5 = "da855ff838250f45d528a5a05692f14e",
file_name = "MyFile.docx",
file_type = "docx",
features = new[] { "te" },
te = new te
{
reports = new[] { "pdf", "xml" },
images = new a[] { new a { id = "7e6fe36e-889e-4c25-8704-56378f0830df", revision = 1 }, new a { id = "e50e99f3-5963-4573-af9e-e3f4750b55e2", revision = 1 } }
},
}
};
string json = JsonConvert.SerializeObject(myjason, Newtonsoft.Json.Formatting.Indented);
Console.WriteLine(json);
}
public class myJsonClass
{
[JsonProperty("request")]
public requestClass Request { get; set; }
}
public class requestClass
{
public string md5 { get; set; }
public string file_name { get; set; }
public string file_type { get; set; }
public string[] features { get; set; }
public te te { get; set; }
}
public class a
{
public string id { get; set; }
public int revision { get; set; }
}
public class te
{
public string[] reports { get; set; }
public a[] images { get; set; }
}
Output:
{
"request": {
"md5": "da855ff838250f45d528a5a05692f14e",
"file_name": "MyFile.docx",
"file_type": "docx",
"features": [
"te"
],
"te": {
"reports": [
"pdf",
"xml"
],
"images": [
{
"id": "7e6fe36e-889e-4c25-8704-56378f0830df",
"revision": 1
},
{
"id": "e50e99f3-5963-4573-af9e-e3f4750b55e2",
"revision": 1
}
]
}
}
}
I have a webservice where I need to receive multiple parameters, one of which is a list.
This is the webservice method:
[HttpPost("complete/{requestId}")]
public IActionResult CompleteRequest([FromBody] RequestComplete requestComplete, int requestId)
{
if (requestId == 0)
{
return BadRequest();
}
if (requestComplete == null)
{
return BadRequest();
}
// execute code
}
The RequestComplete class looks like this:
public class RequestComplete
{
public int RequestId { get; set; }
public int UserId { get; set; }
public string emailCC { get; set; }
public string emailSubject { get; set; }
public string calcsNeeded { get; set; }
public string ssiComment { get; set; }
public List<CompleteFileUpload> completeFiles { get; set; }
}
And the CompleteFileUpload class like this:
public class CompleteFileUpload
{
public int RequestFileId { get; set; }
}
From PostMan I use a post body like this:
{
"calcsNeeded" : "4",
"completeFiles": {"RequestFileId": "384"},
"emailCC" : "test#email.com",
"emailSubject": "subject here",
"ssiComment":"Thanks for your request."
}
My expectation is that the json posted by Postman will be formatted properly to be accepted by the CompleteRequest method. However, it does not. If I remove the completeFiles section of the json, it runs fine.
What am I missing?
The definition of "completeFiles" in the JSON does not define a JSON array, it defines a single object. That JSON would be valid if the definition was:
public class RequestComplete
{
...
public CompleteFileUpload completeFiles { get; set; }
}
Try changing the JSON to:
{
"calcsNeeded" : "4",
"completeFiles": [ {"RequestFileId": "384"}, {"RequestFileId": "123"} ],
"emailCC" : "test#email.com",
"emailSubject": "subject here",
"ssiComment":"Thanks for your request."
}
Hope this helps