Not Able To Parse Web Response Content - json

I'm trying to retrieve JSON from a URL and read it into my application. I am having an issue when reading the WebResponse. When the response is read, it comes back as only Symbols and is not properly formatted json.
How do I get a properly formatted JSON after streaming my WebResponse?
My Javascript is as follows:
function getJsonWM() {
//var stringedData = JSON.stringify(ajaxData);
$.ajax({
type: "GET",
url: '/Default/GetQuestionByHighestScore',
//data: JSON.stringify("{}"),
contentType: "application/json; charset=utf-8",
//dataType: "json",
success: function (data) {
var label = $("#lblResults");
var json = JSON.stringify(data);
label.text(json);
//if (data.d.Pin == undefined) {
// alert("Error: " + data.d.ErrorMessage);
//} else {
// alert("Please record the following PIN: \r\n \r\n" + data.d.Pin);
//}
},
error: function (data) {
//alert("Error: " + data.d.ErrorMessage);
}
});
}
$(function() {
//$("#btnSubmit").click(getJson);
$("#btnSubmit").click(getJsonWM);
});
My controller is as follows:
public class DefaultController : Controller
{
private const string questionUrl = "https://api.stackexchange.com/2.1/questions?order=desc&sort=activity&site=stackoverflow";
public string GetQuestionByHighestScore()
{
List<Item> list = new List<Item>();
var json = GetJson(questionUrl);
var array = JsonConvert.DeserializeObject<Item>(json);
return list.OrderByDescending(x => x.Score).FirstOrDefault().ToString();
}
public string GetJson(string url)
{
var myWebRequest = (HttpWebRequest)HttpWebRequest.Create(url);
myWebRequest.Method = "GET";
myWebRequest.ContentType = "application/json";
var myWebResponse = (HttpWebResponse)myWebRequest.GetResponse();
string strResponse = String.Empty;
var encoding = Encoding.Default;
using (var reader = new StreamReader(myWebResponse.GetResponseStream(), encoding))
{
//JavaScriptSerializer js = new JavaScriptSerializer();
strResponse = reader.ReadToEnd();
}
return strResponse;
}
}
My strResponse object is as follows:
"‹\b\0\0\0\0\0\0µ\\\vÛ6¶þ+„\bÚ{G£%Q)‚ÜI“4\t6»iÓtw/”HÙšÑÕä™8Eÿû=‡”ly,y$·iÐ%òóññ¼éßi#ózñô[4|‰wÑe!›ÅÅ\"ßdMÚ¬*ÉEZ,ÿw±(ï\vY-žþ¶¨äzÓð&-‹ÅSÛv/›ZVשX<umæYžÝ¾i¶k¹x\nÝ—iÝÈJ\n`ËãX®›ëŠ7ÐÄØÅb]•IšÉë4çKì½jšuýÔ4Ó˺áñíeš/7Õe\\ææÏôêþß—7ëåóú™í°'Ëg60i½Îøöºà9’¼ÝþÄsÙÅ\"K‹Û–!ðSÜÊ;Y%Yy¯øák³²Yßn+EøûÅ\"­¯yQß«!?MxVË‹Å]*ï¯ãrS40i\a&¢:ìÞ\\,긬`|1¯›k7é]Úl¯…šªM=›:®ãBÏW¯ßd‡¡¶¤R¤Í™­Öô׬™Zih`®CŸfGSmiLµ·Æns\r؃Ï[#^ÉøVVFÝȸ1Š²1jÙMiðÂH\và\\ÄÒ(|Ô}`‘#®û{ÅòçŽ%Q,IË’ü]u'À’\0KÒ”„¤cIÊ[–¿_ìÁ˜oë_3ø’uY7ËJê\ažó/eaÀÞÔ«4iF‘é[¬‡L'p=Ë\n§\"3\bÆ‘y¹¬øo¸¦þhºŒ\a¡—D‚òÀŠBG¸’{^苘E2òe\v[ñ,²hÒ¸,žTÏ>üð$Âñ\aÞ4+m–“ÜÎÐ\\ï(§ ù!­©#v¼a ·MG`\rÄsÁŠ4fšÃFÜIc\rÝÊ*ï#\bs4 wµ565b¸*ïb“G\0„=*ßjZÒ£E´-Q´DÑ ½niûð[o›•’$u\t(nêq!Ø—¥>sN!m\fXÙÊ¿\\–å2“H\nøh\0'jYŒ¼æÅ««7âê­yµû¯÷ùÅ'35~i^_Õ/£[s½*›RËÊ/ˆºc€}¿ªÒšü$y6aíÌÌIá\0鈹gcÌG0qTXj²caÉ|¶°“g°oŒ0\b²PcÁÐÒÂÈ%#DôwµïbN÷¾Ô½¿ù–´ýû(«6ÑÖ#ÆÓ¬NøŒ˜“YkœÀºjÇ¥\\yãû¨f#oL¤IGDÂñ¤ð…å$qB=ϱœ€ZüBo–H“U&\vqS®øtíÜNÉìÓNÀ.˜‚¶ÏÂœZvh\ràÊòèl¹†4æýŠ7µc9¨7C&I§°ŠÆ=ß* É\fÕ0Gí,61ô­7ÑþB½è^ö0øà"

Looks like the server returns gzip encoded response. So make sure that you have set the AutomaticDecompression property when making your HTTP request:
public string GetJson(string url)
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Headers[HttpRequestHeader.AcceptEncoding] = "gzip, deflate";
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
using (var response = (HttpWebResponse)request.GetResponse())
using (var stream = response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
string strResponse = reader.ReadToEnd();
return strResponse;
}
}
Also please get rid of those application/json content types. You are making a GET request which doesn't have a body - you are not sending any JSON. Also get rid of the contentType switch in your jQuery AJAX request (same reason).

Related

get some word from return String - rest function

In that case I've already tried to get the returned JSON, but when I use the JSON.parse and the JSON.stringify it returns undefined. If I do not use and leave only the data = data.toString('utf8');, return:
!!xxxxxxxxxxxxxxxxxxxxxxxxxxxxx.rest.schema.CtLoginResp {error: null, sessionID: 6dMX4uGVurFdLRL+hW4F2kIW}
And I want the sessionid... But If i try get this, return undefined, I try JSON.parse, JSON.stringify, see that:
My code:
var Client = require('./lib/node-rest-client').Client;
var client = new Client();
var dataLogin = {
data: { "userName":"xxxxxxxxxxx","password":"xxxxxxxxxxxxx","platform":"xxxxxxx" },
headers: { "Content-Type": "application/json" }
};
client.registerMethod("postMethod", "xxxxxxxxxxxxxxxxxxxx/login", "POST");
client.methods.postMethod(dataLogin, function (data, response) {
// parsed response body as js object
// console.log(data);
// raw response
if(Buffer.isBuffer(data)){ // if i remove buffer return is 21 22 etc etc
data = data.toString('utf8'); // this return all but String
var outputTe = data;
var res = outputTe.split(" ", 4);
res = res[3].split("}", 1);
}
console.log(res);
});
Image return:
In the case if i does not use Buffer return is 21 34 56 etc.
But if I use return is all the STRING data.toString(); inside the image...
EDIT.
I try use split but return just the string "sessionid" see the other image:
I try same code inside W3 schools and does not work inside my code but in W3 school test works fine:
1)
2)
In the case I use regex:
client.methods.postMethod(dataLogin, function (data, response) {
if(Buffer.isBuffer(data)){
data = data.toString('utf8');
console.log(data);
var re = /(sessionID: )([^,}]*)/g;
var match = re.exec(data);
var sessionid = match[2]
console.log(sessionid);
openRequest(numberOrigin);
}
});

How to extract JSON data received in controller in a String variable

Could you please let me know how to extract JSON data received in a string variable in controller. Please see the attachment.Thanks.
$("#btn1").on("click", function () {
var i = new Array();
var j = 0;
$("#sl1").multiselect("getChecked").map(function () {
alert(this.value);
i.push(this.value);
//i[j] = this.value;
//j++;
}).get();
var postData = { values: i };
jQuery.ajaxSettings.traditional = true;
$.post('/TodoList/searchdata', postData, function (data) {
alert(data.Result);
});
//$.ajax({
// type: "POST",
// url: "/TodoList/searchdata",
// data: postData,
// success: function (data) {
// alert(data.Result);
// },
// dataType: "json",
// traditional: true
//});
});
Controller code:-
public void searchdata(String[] values)
{
//{
// JavaScriptSerializer js = new JavaScriptSerializer();
// List<String[][]> data=js.Deserialize<List<String[][]>>(i);
Console.WriteLine(values);
}
You can use Newtonsoft Json library https://www.nuget.org/packages/Newtonsoft.Json/
So As mentioned in the below link use it like below
string json = #"{ 'Email': 'james#example.com', 'Active': true,
'CreatedDate': '2013-01-20T00:00:00Z', 'Roles': [
'User', 'Admin' ] }";
Account account = JsonConvert.DeserializeObject(json);
if you doesn't have model , just use like below
var model = JsonConvert.DeserializeObject(json);
the check the below link
http://www.newtonsoft.com/json/help/html/deserializeobject.htm
Try this
JavaScriptSerializer js = new JavaScriptSerializer();
var data=js.Deserialize<Dictionary<string, List<string>>>(i);
Use This Class :
public class JsonAttributeClass<T> where T:class ,new()
{
public static string EntityToJsonConvertor(T entity)
{
string json = JsonConvert.SerializeObject(entity);
return json;
}
public static T JsonToEntityConvertor(string json)
{
var entity = JsonConvert.DeserializeObject<T>(json);
return entity;
}
}

Obtaining JSON data from server into $.ajax call

I have a problem with JSON and JQUERY. In my web application I submit some data (through an $.ajax call) to a servlet and want to receive back some informations from this servlet once it has done.
I'm using JSONObject in this way:
function check(){
$.ajax({
url: "/check",
type: "POST",
dataType: "json",
success: on_check_ok,
error: function(){
alert("something wrong happened");
},
data: {
players_code: $("#players_code").val(),
},
});
return false;
}
function on_check_ok(data) {
var json = data;
$("#display").text(json.check); //"display" is a <div> into index.html
};
and this is doPost() method in my servlet code:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
response.setContentType("application/json");
PrintWriter out = response.getWriter();
String code_array = request.getParameter("players_code");
System.out.println("Player's code is: " + code_array);
int arr = Integer.parseInt(code_array);
LinkedList<Integer> stack = new LinkedList<Integer>();
while(arr > 0){
stack.push(arr%10);
arr = arr/10;
}
int index = 0;
while(!stack.isEmpty()){
array[index] = (int)stack.pop();
index++;
}
mm.checkGuess(array);
response.getWriter().write(mm.ris + " ");
tries++;
System.out.println("TRIES: " + tries);
JSONObject obj = new JSONObject();
obj.put("check", tries);
String json = obj.toString();
out.write(json);
System.out.println("JSON " + json);
}
}
but cannot get displayed any information. Seems that JSONObject has been created correctly, since I can display it on console. I'm having hard times on getting this data back to javascripts.
That's my code, what I'm doing wrong? Or, is there an alternative way to get the same result? thanks for the help!

extract data from json

I have a json data coming from wcf servicein jquery like this
GetBedTypeList1Result1 is function in wcf
{
"GetBedTypeList1Result":[
{"Code":23,"CompanyCode":null,"Decode":"1 Class New Born Bed","DivisionCode":0,"LocationCode":0,"admDueDepAmt":0,"bedTypeCode":0,"caseTypeCode":0,"caseTypeDecode":null,"ptnClassCode":0,"ptnClassDecode":null,"rsvDueDepAmt":0},
{"Code":22,"CompanyCode":null,"Decode":"1st Class Bed","DivisionCode":0,"LocationCode":0,"admDueDepAmt":0,"bedTypeCode":0,"caseTypeCode":0,"caseTypeDecode":null,"ptnClassCode":0,"ptnClassDecode":null,"rsvDueDepAmt":0},
{"Code":5,"CompanyCode":null,"Decode":"Classique Bed","DivisionCode":0,"LocationCode":0,"admDueDepAmt":0,"bedTypeCode":0,"caseTypeCode":0,"caseTypeDecode":null,"ptnClassCode":0,"ptnClassDecode":null,"rsvDueDepAmt":0}
],
"strErrMsg":"Y",
"chrErrFlg":"c"
}
I am calling service like below
function CallWcfService() {
//alert("CallWcfServicexxxx");
jQuery.ajax
(
{
type: Type,
url: Url,
data: parameters,
contentType: ContentType, // content type sent to server
dataType: DataType, //Expected data format from server
cache: "false",
crossDomain: true, //Same result if i remove this line
processdata: ProcessData, //True or False
success: function (msg)
{
ServiceSucceeded(msg);
},
error: ServiceFailed// When Service call fails
}
);
}
function callService()
{
DataType = "json";
Type = "GET";
var par = 4;
parameters = null;
Url = "http://192.168.2.42/CWSERVERWCF/bedtypemasterService.svc/GetBedTypeList?callback=?";
parameters = "{'strErrMsg':'1'},{'chrErrFlg':'A'},{'pcompanycode':'0'},{'pdiv':'1'},{'ploc':'1'}";
// alert(parameters);
ContentType = "application/json; charset=utf-8";
ProcessData = true;
//alert("sssssasasadsds");
CallWcfService();
}
I am trying to fetch data but not getting lke below
function ServiceSucceeded(result)
{
if (DataType == "json")
{
var obj = jQuery.parseJSON(JSON.stringify(JSON.stringify(result)));
for (var x = 0; x < obj.length; x++)
{
}
}
}
In obj.length count of characters is coming and jQuery.parseJSON(result) is not working
Please help
If the result is json there is no need to parse it in this way. jQuery.ajax will return a javascript object if the datatype is set to json.
So in your ServiceSucceeded function you may operate on the result variable directly. If you are trying to iterate over the bed types change your for loop to something like this:
for (var i = 0; i < result.GetBedTypeList1Result.length; i++) {
// ...do stuff
// var bed = result.GetBedTypeList1Result[i]]
}
Try using JSON.parse(result) instead of: var obj = jQuery.parseJSON(JSON.stringify(JSON.stringify(result)));
Also, since you've mentioned the dataType as 'json' in your $.ajax call, your response should already be in JSON format with no parsing required.

How to send/post the JSON request in windowsphone

Anyone knows how to send the request using JSON content in windowsphone. I had the JSON parameters how to post it.
Simply serialize the data in JSON, and write it as a POST request to the server. Here's how I do it in one of my apps:
private static IObservable<T> GetDataAsync<T, TRequest>(TRequest input, string address)
{
var request = HttpWebRequest.Create(address);
request.Method = "POST";
var getRequestStream = Observable.FromAsyncPattern<Stream>(
request.BeginGetRequestStream,
request.EndGetRequestStream);
var getResponse = Observable.FromAsyncPattern<WebResponse>(
request.BeginGetResponse,
request.EndGetResponse);
return getRequestStream()
.SelectMany(stream =>
{
try
{
using (var writer = new StreamWriter(stream))
writer.WriteLine(JsonConvert.SerializeObject(input));
}
catch
{
// Intentionally ignored.
}
return getResponse();
})
.Select(webResponse =>
{
using (var reader = new StreamReader(webResponse.GetResponseStream()))
return JsonConvert.DeserializeObject<T>(reader.ReadToEnd());
});
}