Read Json data from file - c#

Hello i'm trying to read json data from a text file but it doesn't work.
when i try to get data from a website then it works fine.
Anyone know a solution to fix this problem ?
thanks in advance.
private void Form1_Load(object sender, EventArgs e)
{
string path = #"C:\Users\spacefrog\Documents\Visual Studio 2017\Projects\json_test_solution\json_test\bin\Debug\test.json";
// Stream stream = File.OpenRead(path);
WebClient client = new WebClient();
Stream stream = client.OpenRead("https://www.cryptocompare.com/api/data/coinlist/"); // works perfect
/*
Stream stream = client.OpenRead(path); // doesn't work
Stream stream = File.OpenRead(path); // doesn't work
*/
/* File Data content (same as website)
{
"Response": "Success",
"Message": "Coin list succesfully returned!",
"BaseImageUrl": "https://www.cryptocompare.com",
"BaseLinkUrl": "https://www.cryptocompare.com",
"Data": {
"LTC": {
"Id": "3808",
"Url": "/coins/ltc/overview",
"ImageUrl": "/media/19782/ltc.png",
"Name": "LTC",
"CoinName": "Litecoin",
"FullName": "Litecoin (LTC)",
"Algorithm": "Scrypt",
"ProofType": "PoW",
"SortOrder": "2"
}
...
},
"Type": 100
}
*/
StreamReader reader = new StreamReader(stream);
JObject json = JObject.Parse(reader.ReadLine());
stream.Close();
MessageBox.Show((string)json["Response"]);
}

JObject json = JObject.Parse(reader.ReadLine());
How should the JSON.NET Parser parse the first line? Looking at your comment, the first line seems to be
{
Does not look like a valid JSON object. Take a look at the ReadToEnd method.
By the way, you may want to use the StreamReader within a using scope.

You don't have to use a temp file to parse that json
WebClient webClient = new WebClient();
var json = webClient.DownloadString("https://www.cryptocompare.com/api/data/coinlist/");
var rootObj = JsonConvert.DeserializeObject<SOTest.RootObject>(json);
//OR var jObj = JObject.Parse(json);
if you really want to save to a file you can use
webClient.DownloadFile(url,filename);
or write the json above to a file
File.WriteAllText(filename, json);
or if you want to go the client.OpenRead way
var f = File.Create(filename);
stream.CopyTo(f);
public class SOTest
{
public class DataItem
{
public string Id { get; set; }
public string Url { get; set; }
public string ImageUrl { get; set; }
public string Name { get; set; }
public string Symbol { get; set; }
public string CoinName { get; set; }
public string FullName { get; set; }
public string Algorithm { get; set; }
public string ProofType { get; set; }
public string FullyPremined { get; set; }
public string TotalCoinSupply { get; set; }
public string PreMinedValue { get; set; }
public string TotalCoinsFreeFloat { get; set; }
public string SortOrder { get; set; }
}
public class RootObject
{
public string Response { get; set; }
public string Message { get; set; }
public string BaseImageUrl { get; set; }
public string BaseLinkUrl { get; set; }
public Dictionary<string,DataItem> Data { get; set; }
public int Type { get; set; }
}
}

Related

Parse Json Response Data

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

Facing issue while deserializing the http resposne [duplicate]

This question already has an answer here:
Deserializing JSON into an object
(1 answer)
Closed 7 years ago.
I am using JavaScriptserializer to deserialize the HTTP response and convert back to object.
Code to retrieve the response:
using (var response = (HttpWebResponse)request.GetResponse())
{
var responseValue = string.Empty;
if (response.StatusCode != HttpStatusCode.OK)
{
var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
throw new ApplicationException(message);
}
using (var reader = new StreamReader(response.GetResponseStream()))
{
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
var myobj = js.Deserialize<List<NPIObj>>(objText);
}
I am getting JSON string as below:
objText:
{
"NPI": [
{
"NPI": "1003000118",
"EntityType": "Organization",
"IsOrgSubpart": "N",
"OrgName": "STEVEN ENGEL PEDIATRICS",
"FirstLineMailingAddress": "1700 NEUSE BLVD",
"MailingAddressCityName": "NEW BERN",
"MailingAddressStateName": "NC",
"MailingAddressPostalCode": "28560-2304",
"MailingAddressCountryCode": "US",
"MailingAddressTelephoneNumber": "252-637-3799",
"MailingAddressFaxNumber": "252-633-0944",
"FirstLinePracticeLocationAddress": "1700 NEUSE BLVD",
"PracticeLocationAddressCityName": "NEW BERN",
"PracticeLocationAddressStateName": "NC",
}
]
}
The issue happens I am able to get JSON response in the objText variable.
But when i try to deserialize the reponse to NPIObj,the count is coming as 0.
var myobj = js.Deserialize<List<NPIObj>>(objText);
myobj variable is having count as 0,even I am receiving the JSON response.
Here is my NPIObj class:
public class NPIObj
{
public string EntityType { get; set; }
public string FirstLineMailingAddress { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string MailingAddressCityName { get; set; }
public string MailingAddressCountryCode { get; set; }
public string MailingAddressPostalCode { get; set; }
public string MailingAddressStateName { get; set; }
public string MiddleName { get; set; }
public string NamePrefix { get; set; }
public string NPI { get; set; }
public string OrgName { get; set; }
public string SecondLineMailingAddress { get; set; }
}
Can anyone help me out how can i get the response to NPIObj?
You have a root property in your json: NPI. So you are not deserializing the array but the root object.
Create another class:
public class NPIRoot
{
public List<NPIObj> NPI { get; set; }
}
Then
var myobj = js.Deserialize<NPIRoot>(objText);

Read Json from file and display [duplicate]

This question already has answers here:
Android app Json
(2 answers)
Closed 7 years ago.
I writing android app and have API
Writing API to file like this
Code of writing:
string url2 = "http://new.murakami.ua/?mkapi=getProducts";
JsonValue json = await FetchAsync(url2);
string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
string filename = System.IO.Path.Combine(path, "myfile.txt");
using (var streamWriter = new StreamWriter(filename, true))
{
streamWriter.Write(json.ToString());
streamWriter.Close();
}
ParseAndDisplay1(json);
ParseAndDisplay2(json);
ParseAndDisplay3(json);
ParseAndDisplay4(json);
ParseAndDisplay5(json);
ParseAndDisplay6(json);
ParseAndDisplay7(json);
ParseAndDisplay8(json);
}
private async Task<JsonValue> FetchAsync(string url)
{
// Create an HTTP web request using the URL:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
request.ContentType = "application/json";
request.Method = "GET";
// Send the request to the server and wait for the response:
using (WebResponse response = await request.GetResponseAsync())
{
// Get a stream representation of the HTTP web response:
using (Stream stream = response.GetResponseStream())
{
// Use this stream to build a JSON document object:
JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));
//dynamic data = JObject.Parse(jsonDoc[15].ToString);
Console.Out.WriteLine("Response: {0}", jsonDoc.ToString());
// Return the JSON document:
return jsonDoc;
}
}
}
And I need to read some fields from file
I try to do it like this but it didn't work
Code:
private void ParseAndDisplay1(JsonValue json)
{
TextView productname = FindViewById<TextView> (Resource.Id.posttittle);
TextView price = FindViewById<TextView> (Resource.Id.price);
TextView weight = FindViewById<TextView> (Resource.Id.weight);
productname.Click += delegate {
var intent404 = new Intent (this, typeof(SoupesDetailActivity1));
StartActivity (intent404);
};
string path = System.Environment.GetFolderPath (System.Environment.SpecialFolder.Personal);
string filename = System.IO.Path.Combine (path, "myfile.txt");
using (var streamReader = new StreamReader (filename, true)) {
JsonValue firstitem = json [81];
productname.Text = firstitem ["post_title"];
price.Text = firstitem ["price"] + " грн";
weight.Text = firstitem ["weight"] + "г";
}
}
Can you help me with this problem?
Here's a simple way to read the JSON and manipulate it using Json.NET that you can install from Xamarin:
var url = "http://new.murakami.ua/?mkapi=getProducts";
string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
// Since you're just downloading the json you can use a webclient
using (var wc = new WebClient())
{
// Download the json data
var jsonData = await wc.DownloadStringTaskAsync(new Uri(url));
// Save the json data
File.WriteAllText(Path.Combine(path, "myfile.txt"), jsonData);
// Deserialize the Json into a list of object of the type YourObject
List<YourObject> list = JsonConvert.DeserializeObject<List<YourObject>>(jsonData);
// Do whatever you want to do with the data
foreach (var yourObject in list)
{
// this is just an example
Console.WriteLine(yourObject.post_title);
}
}
And this is the definition of the YourObject class:
// this will hold the deserialized objects and make it easy to use
// You can delete properties you don't need
public class YourObject
{
public int ID { get; set; }
public string post_author { get; set; }
public string post_date { get; set; }
public string post_date_gmt { get; set; }
public string post_content { get; set; }
public string post_title { get; set; }
public string post_excerpt { get; set; }
public string post_status { get; set; }
public string comment_status { get; set; }
public string ping_status { get; set; }
public string post_password { get; set; }
public string post_name { get; set; }
public string to_ping { get; set; }
public string pinged { get; set; }
public string post_modified { get; set; }
public string post_modified_gmt { get; set; }
public string post_content_filtered { get; set; }
public int post_parent { get; set; }
public string guid { get; set; }
public int menu_order { get; set; }
public string post_type { get; set; }
public string post_mime_type { get; set; }
public string comment_count { get; set; }
public string filter { get; set; }
public object img_url { get; set; }
public string visibility { get; set; }
public string price { get; set; }
public string weight { get; set; }
public string energy { get; set; }
public string sku { get; set; }
public int category { get; set; }
}

converting from json to c# class object

I try to convert from json to c# class object, cause my final step will be put this all data into local db. I have no problem with taking this data like one big string, so the Url is good typed, but it's not my goal.
this is the json data, here we have two objects
[{"id":"1","category":"1","name":"good 1","prize":"12.3","prize2":"13.4","elements":"row,column,paper","secid":"2131","description":"nice","quality":"best","dateofcoming":"2013-12-20 18:08:50","date":"2013-12-20 00:00:00"},
{"id":"2","category":"2","name":"good","prize":"14.3","prize2":"15.4","elements":"up,down,left","secid":"2132","description":"nc","quality":"best","dateofcoming":"2013-12-20 18:10:55","date":"2013-12-20 00:00:00"}]
I try by this way which I found in the book:
private void getBookData()
{
// we creating the request details to the site which give us
// back the json data
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("here is my adress");
request.Accept = "and header";
// starting the request
request.BeginGetResponse(callback_with_food_info, request);
}
private void callback_with_food_info(IAsyncResult ar)
{
HttpWebRequest request = (HttpWebRequest)ar.AsyncState;
// we get the response
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(ar);
DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(ListOfObjects));
Stream responseStream = response.GetResponseStream();
ListOfObjects listOfobj = (ListOfObjects)deserializer.ReadObject(responseStream);
String fsdfsdf = "how how how";
}
and in the row when we ReadObject
ListOfObjects listOfobj = (ListOfObjects)deserializer.ReadObject(responseStream);
I get exception "System.InvalidCastException", my List class look like this and it was created by http://json2csharp.com/
public class DetailsOfObject
{
public string id { get; set; }
public string category { get; set; }
public string name { get; set; }
public string prize { get; set; }
public string prize2 { get; set; }
public string elements { get; set; }
public string secid { get; set; }
public string description { get; set; }
public string quality { get; set; }
public string dateofcoming { get; set; }
public string date { get; set; }
}
public class ListOfObjects
{
public DetailsOfObject list {get; set;}
}
Any advice how to finally convert this json data
You need to add Data attributes to model
[DataContract]
public class DetailsOfObject
{
[DataMember]
public string id { get; set; }
and change deserialize line
List<DetailsOfObject> listOfobj = (List<DetailsOfObject>)deserializer.ReadObject(responseStream);

JavaScriptSerializer, Parsing Json from HttpRequest, put pars into a table to be displayed

I made a call to a web server called Sample ApI. I want to be able to parse that data that's in json or xml, either would be nice and display it in a table format. This is what I have so far.
All I want is to be able to parse the data that's in this string _responseAsString and display a table. I don't know how to start it, I just know JavaScriptSerialzer parseXXX = new Java...lizer(). Please help me or assist in the right direction.
public class Event
{
public string event_key { get; set; }
public string user_token { get; set; }
public string event_set_key { get; set; }
public string event_type { get; set; }
public string event_date { get; set; }
public string event_amount { get; set; }
public string event_location_key { get; set; }
public string event_location_name { get; set; }
public string event_location_city { get; set; }
public string event_location_state { get; set; }
public string event_location_country { get; set; }
public string event_acknowledged { get; set; }
}
public ActionResult GetEvent()
{
try
{
string at = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
string et = "KI2XfwQNByLPFdK4i3a74slLT7sjjzYRi9RR7zEtCoQ%3D";
string t = "20111128183020";
string _checkingUrl = String.Format("http://172.22.22.10/SampleAPI/Event/GetEvents?at={0}&et={1}&t={2}&responseFormat=json", at, et, t);
System.Net.HttpWebRequest request=System.Net.WebRequest.Create(_checkingUrl) as System.Net.HttpWebRequest;
System.Net.HttpWebResponse response=request.GetResponse() as System.Net.HttpWebResponse;
System.IO.StreamReader _readResponse=new System.IO.StreamReader(response.GetResponseStream());
//The encrypted dynamics response in either xml or json
string _responseAsString=_readResponse.ReadToEnd();
JavaScriptSerializer parseResponse = new JavaScriptSerializer();
List<Event> events = parseResponse.Deserialize<List<Event>>(_responseAsString);
// this below is to make sure i was receiving my json data.
return Content(_responseAsString);
_readResponse.Close();
}
catch (Exception e)
{
//log error
}
return View();
}
This is the json data I receive when I make the http request:
"[{\"event_key\":\"cc2a1802-2b04-4530-ad50-0d4f0ed19dd3\",\"user_token\":\"40e62a11-40c4-408d-8cdd-1293cbaf9a41\",\"event_set_key\":\"615017f2-ae28-4b8d-9def-cf043642b928\",\"event_type\":\"Arrival\",\"event_date\":\"6/20/2011
4:15:28
PM\",\"event_amount\":\"100\",\"event_location_key\":\"50fc1c22-d77b-4a91-b31d-da036827060b\",\"event_location_name\":\"Store2\",\"event_location_city\":\"Pittsburgh\",\"event_location_state\":\"PA\",\"event_location_country\":\"US\",\"event_location_lat\":\"\",\"event_location_long\":\"\",\"event_description\":\"\",\"event_acknowledged\":\"True\"},{\"event_key\":\"2ac9e25e-137c-4a72-8cc5-157d67ea66c1\",\"user_token\":\"58cb4fcd-e140-4232-88c9-06eecb95b63d\",\"event_set_key\":\"00710ca7-f5d7-4c7a-bbfb-95491ae278ef\",\"event_type\":\"Arrival\",\"event_date\":\"9/23/2011
4:15:28
PM\",\"event_amount\":\"45\",\"event_location_key\":\"5a732dd5-9459-4cdd-a980-f3daf1a07343\",\"event_location_name\":\"Store4\",\"event_location_city\":\"Pittsburgh\",\"event_location_state\":\"PA\",\"event_location_country\":\"US\",\"event_location_lat\":\"\",\"event_location_long\":\"\",\"event_description\":\"\",\"event_acknowledged\":\"False\"},{\"event_key\":\"386b1fa1-11b2-48d9-b7f1-4bbe21ced487\",\"user_token\":\"c3d8b7ff-d85f-42a8-98f6-e091b48c2280\",\"event_set_key\":\"dc55843b-f8cf-4e8a-9091-188ce0609fe1\",\"event_type\":\"Arrival\",\"event_date\":\"9/18/2011
4:15:28
PM\",\"event_amount\":\"100\",\"event_location_key\":\"be6d4fb4-c0e3-4303-b70d-7a22b721aa56\",\"event_location_name\":\"Store1\",\"event_location_city\":\"Pittsburgh\",\"event_location_state\":\"PA\",\"event_location_country\":\"US\",\"event_location_lat\":\"\",\"event_location_long\":\"\",\"event_description\":\"\",\"event_acknowledged\":\"False\"}]"
The JSON website has some good information on this.
For older browsers, you would eval the string (with some brackets to make it work):
var myObject = eval('(' + myJsonText + ')');
And these days, we tend to use
JSON.parse(myJsonText);
And server side, in C#
var serializer = new JavaScriptSerializer();
T obj = serializer.Deserialize<T>(myJsonText);
First of all...
If you're just passing through the JSON message returned from some other API, why not just return their response string verbatim (in other words, why deserialize it at all)?
public ActionResult GetEvent()
{
string at = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
string et = "KI2XfwQNByLPFdK4i3a74slLT7sjjzYRi9RR7zEtCoQ%3D";
string t = "20111128183020";
string _checkingUrl = String.Format("http://172.22.22.10/SampleAPI/Event/GetEvents?at={0}&et={1}&t={2}&responseFormat=json", at, et, t);
System.Net.HttpWebRequest request=System.Net.WebRequest.Create(_checkingUrl) as System.Net.HttpWebRequest;
System.Net.HttpWebResponse response=request.GetResponse() as System.Net.HttpWebResponse;
using (var readResponse= new StreamReader(response.GetResponseStream()))
{
return Content(readResponse.ReadToEnd(), "application/json");
}
}
Then read on
It's possible to use a JSON text reader to break apart the JSON message into a table of name/value pairs, but I think that's missing the point in your case. If the message is constant, just create a class that represents each element in the JSON message and parse it. I used json2csharp to stub such a class:
public class Event
{
public string event_key { get; set; }
public string user_token { get; set; }
public string event_set_key { get; set; }
public string event_type { get; set; }
public string event_date { get; set; }
public string event_amount { get; set; }
public string event_location_key { get; set; }
public string event_location_name { get; set; }
public string event_location_city { get; set; }
public string event_location_state { get; set; }
public string event_location_country { get; set; }
public string event_location_lat { get; set; }
public string event_location_long { get; set; }
public string event_description { get; set; }
public string event_acknowledged { get; set; }
}
Then use your favorite JSON serializer to deserialize into a list of these objects:
var serializer = new JavaScriptSerializer();
var events = serializer.Deserialize<List<Event>>(responseAsString);
(I prefer JSON.NET, here's the equivalent to the block above)
var events = JsonConvert.DeserializeObject<List<Event>>(responseAsString);
If you actually do need to be able to read a stream of text and generically create a table of name/value pairs, I'd use JSON.NET's LINQ-to-JSON or the JsonTextReader.

Categories

Resources