Reading from JSON, data not displayed - c#

I'm having this strange problem when i try to access elements in json from javascript. i retreve a json string from a url like so,
// Create Request
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(#"www.someurl.com");
// Create Client
WebClient client = new WebClient();
// Assign Credentials
client.Credentials = new NetworkCredential("username", "pass");
// Grab Data
sjson = client.DownloadString(#"www.someurl.com");
System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
oSerializer.MaxJsonLength = Int32.MaxValue;
sjson = oSerializer.Serialize(sjson);
But when i access this sjson variable from javascript in html code, it doesn't return anything, but if i hard code it, it returns the values, please help on this one. I tried many things but didn't work. I also tried to just pass the retreieved json string without serializing, when i do that the javascript stops working. :( following is the javascript code,
<script type="text/javascript">
var jsons = JSON.parse('<%=sjson%>');
function initialize() {
alert("hahahahaaa");
document.writeln(jsons.Body[0].RowId.SensorIdValue);
//document.writeln(myobject.Body[0].RowId.SensorIdValue);
}
</script>
The issue is
document.writeln(myobject.Body[0].RowId.SensorIdValue);
returns a value if i use the myobject variable, but
document.writeln(jsons.Body[0].RowId.SensorIdValue);
returns nothing when i use it with the parsed value. :(
following is the sample of the json output (response.write) i get after running the serializer via c#,
Please help me on this one..i cant seem to find the problem here.
EDIT:
if it help, the fiollowing is the json string i get straight from the server witout making any serializations,
Few contents of the question have been removed due to owner request

What you're seeing there is doubly JSON-serialized data. You retrieved JSON from the remote server and then JSON encoded it a second time with JavaScriptSerializer. This is a post I wrote about that, in the context of ASMX ScriptServices, which explains in more detail: http://encosia.com/asp-net-web-services-mistake-manual-json-serialization/. Your case isn't exactly the same, but the end result is.
Remove the JavaScriptSerializer code and return the JSON string you retrieved (sjson) instead of serializing it a second time.

You don't need to use a Json serializer because the remote server already returns a JSON encoded string that you could directly use in your page and avoid the double encoding.
So:
public string GetJson()
{
// Create Client
using (WebClient client = new WebClient())
{
// Assign Credentials
client.Credentials = new NetworkCredential("username", "pass");
// Grab Data
return client.DownloadString(
#"www.someurl.com"
);
}
}
and then:
<script type="text/javascript">
var jsons = <%= GetJson() %>;
function initialize() {
alert("hahahahaaa");
document.writeln(jsons.Body[0].RowId.SensorIdValue);
//document.writeln(myobject.Body[0].RowId.SensorIdValue);
}
</script>

Related

How do you send a json object to php backend properly

While using something like this
"
Dictionary<string, string> form = new Dictionary<string, string>
{
{_metajson, JsonConvert.SerializeObject(metaJson)}
};
HttpResponseMessage response = await httpClient.PostAsync(url, new FormUrlEncodedContent(form));
However on the php side of things with $_Request I get the string and all the quotes are turned into " so the json looks like
{"name":"myname"}
Is there a better way to send json to a php backend?
On the PHP end of things I am simply assigning the json which has now lost the quotes and has weird marks with
$json = $_REQUEST["test"];
The json I am sending is in memory, its not saved to a file anywhere. It is very small like shown above and is needed for the purposes of the application I am writing.
Use php://input
php://input is a read-only stream that allows you to read raw data from the request body.
Example:
$json_string = file_get_contents('php://input');
//Converting It to PHP object:
$data = json_decode($json_string );
I was just working with the same problem and here is my solution, it works for me
$data = $_POST['json'] ;
$json = json_decode($data, true);
echo json_encode($json);
afterwards, you can take the $json variable an do whatever you want to do with it
I ended up changing the approach which worked very well
I simply base64 encoded the json to avoid http changing special characters to odd string formats like " to " and what not.
C# side - using this string in the dictionary form
string encodedJson = Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(metaJson)));
PHP side
$encoded_input = $_REQUEST["metajson"];
$base64_decoded_input = base64_decode($encoded_input, true);
if (!$base64_decoded_input)
{
// error out
}
$meta_json = json_encode(json_decode($base64_decoded_input));

Get raw querystring of WebClient in C#

I'm using a WebClient to make a POST request with a query string but I can't see the raw string. This is what I have:
WebClient TheWebClient = new WebClient();
TheWebClient.QueryString.Add("Param1", "1234");
TheWebClient.QueryString.Add("Param2", "4567");
TheWebClient.QueryString.Add("Param3", "4539");
var TheResponse = TheWebClient.UploadValues("https://www.example.com/posturl", "POST", TheWebClient.QueryString);
string TheResponseString = TheWebClient.Encoding.GetString(TheResponse);
//problem is that this only shows the keys
var RawQueryString = TheWebClient.QueryString;
How can I see the actual raw query string?
WebClient.UploadValues doesn't save the request "raw query string" simply because you provided it with them, and it's not gonna change, thus is redundant.
Furthermore, HttpPost requests doesn't use query string for the request payload, it has a url, a message payload; which is appended after the headers, maybe query string. Thus there is nothing new the client class should let you know, so it won't save it.

C# HTTP post , how to post with List<XX> parameter?

using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
string HtmlResult = wc.UploadString(url, "sign=fsadfasdf&charset=utf-8");
}
Server can get value of sign and charset.
But there is a third parameter LIST, which is a list of object (this object is an entity class).
How can I pass this parameter to the server?
I tried to use "sign=fsadfasdf&charset=hhh&list=" + Json(list) as postData (convert List to json string). But the server didn't get value of this list param.
I hate to post 1 line answers with links in them but this has been solved on here before ...
POSTing JsonObject With HttpClient From Web API
HttpClient class is designed to solve exactly this problem, i believe its found in the nuget package "Microsoft.AspNet.WebApi.Client", this should add the namespace "System.Net.Http" to your project.
It's also geared at being completely async which should be nicer to your server!
EDIT:
To post an array / collection you would do something like this ...
var myObject = (dynamic)new JsonObject();
myObject.List = new List<T>();
// add items to your list
httpClient.Post(
"",
new StringContent(
myObject.ToString(),
Encoding.UTF8,
"application/json"));

Consuming web services in C#

I just started playing around with some API's in C#. In my form I had added a service reference http://wsf.cdyne.com/WeatherWS/Weather.asmx. Everything works great and I am able to utilize its library. Now I am trying to use for example http://free.worldweatheronline.com/feed/apiusage.ashx?key=(key goes in here)&format=xml. [I have a key] Now when I try to use it as service reference I am not able to use.
Do I have to call it in my form instead of referencing it? or do some sort of conversion? Also does it matter if its xml or json type?
ASMX is old technology and uses SOAP under the hood. SOAP doesn't tend to work with query string parameters, it takes parameters as part of the message.
ASHX is something different (it could be anything, it's one way to write a raw HTML/XML page in .NET), so you can't transfer the method for calling one to the other. It also won't have a service reference, it's likely you request it via a raw HTTP request. You'll need to consuly the service documentation to discover how to use it.
worldweatheronline doesn't return a SOAP-XML that is consumable by a WebService client. Therefore you should download the response and parse it as done with many REST services.
string url = "http://free.worldweatheronline.com/feed/apiusage.ashx?key=" + apikey;
using (WebClient wc = new WebClient())
{
string xml = wc.DownloadString(url);
var xDoc = XDocument.Parse(xml);
var result = xDoc.Descendants("usage")
.Select(u => new
{
Date = u.Element("date").Value,
DailyRequest = u.Element("daily_request").Value,
RequestPerHour = u.Element("request_per_hour").Value,
})
.ToList();
}
Also does it matter if its xml or json type?
No, at the end you have to parse the response by yourself.
string url = "http://free.worldweatheronline.com/feed/apiusage.ashx?format=json&key=" + apikey;
using (WebClient wc = new WebClient())
{
string json = wc.DownloadString(url);
dynamic dynObj = JsonConvert.DeserializeObject(json);
var jArr = (JArray)dynObj.data.api_usage[0].usage;
var result = jArr.Select(u => new
{
Date = (string)u["date"],
DailyRequest = (string)u["daily_request"],
RequestPerHour = (string)u["request_per_hour"]
})
.ToList();
}
PS: I used Json.Net to parse the json string

HTTP POST with JSON object returned c#

I am trying to create a HTTP Post that returns a JSON object with 2 attributes.
Details are below:
HTTP POST to http://text-processing.com/api/sentiment/ with form encoded data which contains a string. A JSON object response with 2 attributes is retuned; lable and negative.
I am tying to do this in c#, which is where I am struggling.
Thank you
You can try using a WebClient like this
WebClient webclient = new WebClient();
NameValueCollection postValues = new NameValueCollection();
postValues.Add("foo", "fooValue");
postValues.Add("bar", "barValue");
byte[] responseArray = webclient.UploadValues(*url*, postValues);
string returnValue = Encoding.ASCII.GetString(responseArray);
MSDN page also has an example.

Categories

Resources