I am trying to export to file the json output of a url. But starting with parsing the json output, I got an error of Bad request. I can't understand why, because when i manually input the url on web, it has a valid result.
using System;
using System.IO;
using System.Web;
using System.Net;
namespace web
{
class Program
{
static void Main(string[] args)
{
var json = new WebClient().DownloadString("http://steamcommunity.com/market/pricehistory/?country=DE¤cy=3&appid=570&market_hash_name=Helm%20of%20the%20Guardian%20Construct");
Console.WriteLine(json);
Console.ReadLine();
}
}
}
Related
Using this example for my MVC project, I want to log my exception on a file, even without attaching a debugger, when I run my project after publishing it on IIS, not in output window when the project is in debug.
My code is the same as the one presented in the link.
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
namespace ServerSide
{
public class MyLoggerService : DevExpress.XtraReports.Web.ClientControls.LoggerService
{
public override void Info(string message)
{
System.Diagnostics.Debug.WriteLine("[{0}]: Info: '{1}'.", DateTime.Now, message);
}
public override void Error(Exception exception, string message)
{
System.Diagnostics.Debug.WriteLine("[{0}]: Exception occured. Message: '{1}'. Exception Details:\r\n{2}",
DateTime.Now, message, exception);
}
}
}
How could I change this code in order to make it log exceptions to a file?
In case anyone needs it, the solution is to add in Error method this code:
string filePath = #"C:\ReportDesigner\server\publish\Exceptions.txt";
using (StreamWriter writer = new StreamWriter(filePath, true))
{
writer.WriteLine("-----------------------------------------------------------------------------");
writer.WriteLine("Date : " + DateTime.Now.ToString());
writer.WriteLine();
while (exception != null)
{
writer.WriteLine(exception.GetType().FullName);
writer.WriteLine("Message : " + exception.Message);
writer.WriteLine("StackTrace : " + exception.StackTrace);
exception = exception.InnerException;
}
}
I'm relatively new to working with JSON and would like to deserialize content I downloaded from https://5e.tools/. I could try to anticipate all the tags/fields in a class, but the dataset example (https://www.newtonsoft.com/json/help/html/DeserializeDataSet.htm) looked more convenient so I tried that first:
using Newtonsoft.Json;
using System;
using System.Data;
using System.IO;
namespace _5EToolsConvertor
{
class Program
{
static void Main(string[] args)
{
string json = File.ReadAllText(#"D:\Downloads\5eTools.1.116.8\data\spells\spells-phb.json");
DataSet dataSet = JsonConvert.DeserializeObject<DataSet>(json);
DataTable dataTable = dataSet.Tables["spell"];
Console.WriteLine(dataTable.Rows.Count);
foreach (DataRow row in dataTable.Rows)
{
Console.WriteLine(row["name"] + " - " + row["level"]); // just to check
}
}
}
}
Here is part of the first item from the JSON file:
{"spell":[{"name":"Acid Splash","source":"PHB","page":211,"srd":true,"level":0,"school":"C","time":[{"number":1,"unit":"action"}],"range":{"type":"point","distance":{"type":"feet","amount":60}},"components":{"v":true,"s":true},"duration":[{"type":"instant"}], ...
I get the error:
An unhandled exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll
Unexpected JSON token when reading DataTable: StartObject. Path 'spell[0].range', line 1, position 139.
EDIT 11/30/2020
Advice in the comments suggested moving from a dataset model (spreadsheet) because some of my JSON fields are hierarchical. I've created a class with List<Jobject> for the hierarchical fields like "Time". But, I'd rather end up with all data in vanilla c# objects like Dictionary<string, object>. I'm having trouble converting. What is the best way? This code runs on the full JSON file but prints System.Collections.Generic.List1[Newtonsoft.Json.Linq.JObject]` for every "Time" object.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
namespace _5EToolsConvertor
{
public class Spell
{
public string Name { get; set; }
public string Source { get; set; }
public string Page { get; set; }
public string SRD { get; set; }
public List<JObject> Time { get; set; }
}
class Program
{
static void Main(string[] args)
{
string jsontext = File.ReadAllText(#"D:\Downloads\5eTools.1.116.8\data\spells\spells-phb.json");
JObject json = JObject.Parse(jsontext);
// get JSON result objects into a list
IList<JToken> results = json["spell"].Children().ToList();
// serialize JSON results into .NET objects
IList<Spell> spells = new List<Spell>();
foreach (JToken item in results)
{
// JToken.ToObject is a helper method that uses JsonSerializer internally
Spell spell = item.ToObject<Spell>();
spells.Add(spell);
}
foreach (Spell spell in spells)
{
Console.WriteLine($"Name:{spell.Name} Source:{spell.Source} Page:{spell.Page} SRD:{spell.SRD} Time:{spell.Time}");
}
-david
I have created WebAPI. In it's GET method I want to load local JSON file and pass it as response. So that when someone accesses this endpoint he will get said JSON response. As I'm total newb with WebAPI and JSON I don't know where to start. Even though I searched a lot through web.
I need something like this (don't know actual functions and classes):
// GET api/values
public JSON Get()
{
var json = File.Load(pathtoJSON.json);
return json;
}
As a newb you can tackle this problem in three steps.
STEP I - Go through some basic tutorial on youtube like these.
STEP II - Create s basic controller (get method) and return a simple String like "Hello World!". Try it and see if you are getting the response.
STEP III - Now you got something working then try to read JSON file and send them as response.
EDIT: if still you got issues, here is some very basic code for you reference:
using Newtonsoft.Json;
using System;
using System.IO;
using System.Web.Http;
public class ValuesController : ApiController
{
public UserData Get()
{
UserData userData = null;
using (StreamReader r = new StreamReader(#"C:\testjson.json"))
{
string json = r.ReadToEnd();
userData = JsonConvert.DeserializeObject<UserData>(json);
}
return userData;
}
public class UserData {
[JsonProperty("first_name")]
public string FirstName;
[JsonProperty("last_name")]
public string LastName;
[JsonProperty("age")]
public String Age;
}
}
and testjson.json
{
"first_name":"FirstTest1",
"last_name":"LastTest1",
"age":"25"
}
and the response
using System;
using System.Data;
using System.Net;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.IO;
using System.Web.Script.Serialization;
using System.Web.DynamicData;
using System.Collections;
using System.Data.SqlClient;
namespace ST_977ad26d6e754517ab07c39f6c220cb9
{
[Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
{
public void Main()
{
#region GETRESULTS
string wUrl = "http://182.301.111.121/crm/customers/new?from_date=20170220&20170221;
HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(wUrl);
HttpWebResponse httpWResp = (HttpWebResponse)httpWReq.GetResponse();
string results="";
Stream responseStream = httpWResp.GetResponseStream();
string jsonString = null;
//Set jsonString using a stream reader
using (StreamReader reader = new StreamReader(responseStream)
{
results = reader.ReadToEnd().ToString();
reader.Close();
}
this code is work for other web service but i need to change this code for first login to web service and after login, see data in web service
I have created a New MVC4 Application and by default Newton JSON added to the Package.
I read that it is useful for serializing and deserializing JSON. Is this all it does ?
By default we can send JSON in MVC using JSONResult. and using Stringify in JQuery i can receive as a class in C#.
I know there should be some reason why they added Newton JSON.
As i am new to MVC and starting off new project want to know some insight of which serialize/deserialize to go for ?
Thanks
They added Newtonsoft so that your WebAPI controller can magically serialize your returned object. In MVC 3 we used to return our object like so:
public ActionResult GetPerson(int id)
{
var person = _personRepo.Get(id);
return Json(person);
}
In a Web API project you can return person and it will be serialized for you:
public Person GetPerson(int id)
{
var person = _personRepo.Get(id);
return person
}
Use JsonResult and return Json(yourObject) on a post operation, or Json(yourObject, JsonRequestBehavior.AllowGet) if you're doing a GET operation.
If you want to deserialize Json with the Newton Json.NET, check out http://www.hanselman.com/blog/NuGetPackageOfTheWeek4DeserializingJSONWithJsonNET.aspx
If your project was just an MVC project with no WebApi, then Newtonsoft.Json was not added for returning JsonResults as the JsonResult returned by MVC uses the JavaScriptSerializer as below:
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase))
{
throw new InvalidOperationException(MvcResources.JsonRequest_GetNotAllowed);
}
HttpResponseBase response = context.HttpContext.Response;
if (!String.IsNullOrEmpty(ContentType))
{
response.ContentType = ContentType;
}
else
{
response.ContentType = "application/json";
}
if (ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}
if (Data != null)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
if (MaxJsonLength.HasValue)
{
serializer.MaxJsonLength = MaxJsonLength.Value;
}
if (RecursionLimit.HasValue)
{
serializer.RecursionLimit = RecursionLimit.Value;
}
response.Write(serializer.Serialize(Data));
}
}
In this case it was added because WebGrease has a dependency on it. And the bundling and minification services provided by MVC in System.Web.Optimization have a dependency on WebGrease.
So a default MVC app with no WebApi will have Newtonsoft.Json installed for bundling and minification services not WebApi.
To be clear the JsonResult returned by WebApi in System.Web.Http does use Newtonsoft.Json for it's serialization as below:
using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
namespace System.Web.Http.Results
{
/// <summary>
/// Represents an action result that returns an <see cref="F:System.Net.HttpStatusCode.OK"/> response with JSON data.
/// </summary>
/// <typeparam name="T">The type of content in the entity body.</typeparam>
public class JsonResult<T> : IHttpActionResult
But Newtonsoft.Json is not included in a non WebApi, default MVC project just in case you might decide to use some WebApi, it's there because, as above, WebGrease needs it. Not sure what they're doing in vNext, probably Newtonsoft.Json.