JSON - WepAPI - Unexpected character encountered while parsing value - json

ANY help will be greatly appreciated
I have a Generic class that facilitates WebAPI calls, Its been in place for quite sometime and has had no issue. Today I'm getting an error and not sure where to track the problem. the exact error is
{"Unexpected character encountered while parsing value: [. Path 'PayLoad', line 1, position 12."}
what I'm getting back as the result of the call is
"{\"PayLoad\":[\"file_upload_null20180629155922²AAGUWVP2XUezeM3CiEnSOw.pdf\"],\"Success\":true,\"Message\":\"1 File(s) Uploaded\",\"Exceptions\":[]}"
Which looks right and is what I expect back from the service call
Here is the method that I'm calling that suddenly quit working, and its failing on the last line
public static TR WebApiPost(string serveraddress, string endpoint, object data)
{
HttpResponseMessage msg;
var clienthandler = new HttpClientHandler
{
UseDefaultCredentials = false,
Credentials = new NetworkCredential(user, password, domain)
};
using (var client = new HttpClient(clienthandler) { BaseAddress = new Uri(serveraddress) })
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
msg = client.PostAsync(endpoint, new StringContent(new JavaScriptSerializer().Serialize(data), Encoding.UTF8, "application/json")).Result;
}
var result = msg.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject<TR>(result);
}
AND finally the line that actually makes the call (which should not matter)
returned = CallHelper<ResultStatus<string>>.WebApiPost(serviceurl, sendFileUrl, model);

It's not clear where your web service is getting the value of PayLoad from, so it is very possible that the value has a Byte Order Mark (BOM) at its beginning. This is especially the case if you are returning the content of what was originally a Unicode encoded file.
Be aware that a BOM is NOT visible when you are viewing a string in the debugger.
On your web service, make sure that you are not returning a BOM in the value of PayLoad. Check for this byte sequence at the beginning of the string:
0xEF,0xBB,0xBF
For more information on Byte Order Mark:
https://en.wikipedia.org/wiki/Byte_order_mark

Related

FormatException (FormatException: Unexpected character (at character 1)

I am trying to get data from a json from a link and decode it to display data in a calendar, so it worked fine until this error appears in this line
dynamic jsonAppData = convert.jsonDecode(data.body);
Which trows this:
Exception has occurred. FormatException (FormatException: Unexpected
character (at character 1) <!doctype html><base href="https://accou... ^ )
I don't really know why it is caused, I searched for solutions but I didn't find anything for my case.
I hope you can help me.
Future<List> getDataFromGoogleSheet() async {
Response data = await http.get(
Uri.parse(
"https://script.google.com/macros/s/AKfycbybaFrTEBrxTIni8izFKMQYNNAe7ciVMlqF0OUHyWujjRR2AQ8zDyQzh96tleRKMHSN/exec"),
);
dynamic jsonAppData = convert.jsonDecode(data.body);
final List<Meeting> appointmentData = [];
for (dynamic data in jsonAppData) {
var recurrence = data['byday'];
Meeting meetingData = Meeting(
eventName: data['subject'],
from: _convertDateFromString(data['starttime']),
to: _convertDateFromString(data['endtime']),
background: Colors.grey.shade800,
recurrenceRule: 'FREQ=DAILY;INTERVAL=7;BYDAY:$recurrence;COUNT=10',
);
appointmentData.add(meetingData);
String notes = data['notes'];
}
return appointmentData; }
Your response body is not of json type.
You should check your request before
You can't parse the json because you have to authenticate with google first. If you call the page in the browser, where you are not logged in with Google, then you are redirected to the login page of Google. And my guess is this page is parsed, not the json.

InDesign Socket HTTP response is missing sections

I am automating Adobe InDesign to create documents using JSON data gathered from a web API with a SQL Server backend. I am using the Sockets object to make an HTTP 1.0 call to our server. Sometimes the response received is missing about 1700 characters from various points within the JSON string, yet when I call the same API endpoint using curl or Postman I get a complete and valid response.
The response should be about 150k characters long, and I'm using conn.read(99999999) to read it. In addition, the appearance of the end of the string looks correct, so I don't believe it's any kind of truncation problem.
The problem only seems to occur when I request a UTF-8 encoding. If I request ASCII I get a complete and valid response, but missing various Unicode characters. If I request BINARY I get a complete and valid response but the JavaScript/ExtendScript seems to be handling any multi-byte Unicode characters received as individual bytes, rather than as the Unicode characters we want to display.
Here is an illustration of the behavior I'm seeing, using bogus data...
"Expected" response...
[{"Id":1, "name":"Random Name", "Text":"A bunch of text", "AnotherId": 1}]
"Actual" response...
[{"Id":1, "name":"Random Name", "Text":"A bunc": 1}]
The problem first manifested itself as a JSON2 parsing error, for obvious reasons, but the root of it seems to be the fact that parts of the data are going missing in-transit.
So far we've only seen this problem when making the call using the InDesign Sockets object, and not every response exhibits this behavior.
Any help or insights you could offer would be appreciated.
Here is the function I'm using to call for data...
function httpRequest(url, encoding) {
try {
var response = "";
var hostName = getHostFromUrl(url);
var pathAndQuery = getPathAndQueryFromUrl(url);
var httpGet = "GET ";
httpGet += pathAndQuery;
httpGet += " HTTP/1.0\r\nHost: ";
httpGet += hostName;
httpGet += "\r\n";
var conn = new Socket;
conn.timeout = 30;
//conn.encoding = encoding || "UTF-8";
//conn.charset = "UTF-16";
if (conn.open(hostName + ":80", encoding || "UTF-8")) {
// send a HTTP GET request
conn.writeln(httpGet);
// and read the server's response
response = conn.read(99999999);
conn.close();
}
return parseHttpResponse(response);
}
catch (e) {
$.writeln(e);
$.global.alert("There was a problem making an HTTP Request: " + e);
return null;
}
}
It turns out my handling of the HTTP response was too simplistic and needed extra logic to handle Unicode characters properly.
The solution, in my case, was to use the GetURL method made available by Kris Coppieter here.

HttpClient reads incomplete or malformed string

Im trying to figure out which part of my app (Xamarin Forms and proxy written in PHP) is buggy. Firstly I thought that my proxy (written in PHP) is working incorrectly with long set of data (ie. json containing 1.300.000 characters) and returns malformed response, but every single request with Postman gives me correct JSON, which is successfully decoded with third-party tools. So I assume, proxy is working well.
The problem is (I guess) with decoding response in my Xamarin Forms (2.0.0-beta.22) app. I'm using HttpClient to read response with this code:
response.EnsureSuccessStatusCode();
var entries = new List<HistoryEntry>();
var content = await response.Content.ReadAsStringAsync();
_loggerService.Error(content);
response is just GetAsync response from HttpClient. The problem is: content is randomly incomplete/malformed. Saying this I mean last character is missing (}) or JSON keys/values have additional " character, which breaks everything. Unfortunately, I can make exactly the same requests many times and once it works, once not. I found out that this behavior happens only with large set of data (as I mentioned before, long JSON string).
Is there any possibility that ReadAsStringAsync does not wait for full response or in any way alters my response string? How can I find the reason of wrongly downloaded data?
EDIT 21.05.2019:
Just copied valid JSON (available here: https://github.com/jabools/xamarin/blob/master/json.txt) and returned it from Lumen app by response()->json(json_decode(..., true)) and still the same result. Hope someone will be able to reproduce this and help me with this issue :( More informations in comments.
Used this code in C#:
Device.BeginInvokeOnMainThread(async () =>
{
for (int i = 0; i < 10; i++)
{
var response = await client.GetAsync("<URL_TO_PHP>");
//var response = await client.GetAsync("https://jsonplaceholder.typicode.com/photos");
var content = await response.Content.ReadAsAsync<object>();
Debug.WriteLine("Deserialized: " + i);
}
});

mailboxUsageDetailsRequest returns exception

Replacing MSOnline cmdlets with Microsoft.Graph V1.12.0.
Report mailboxUsageDetailsReport = null;
IReportRootGetMailboxUsageDetailRequestBuilder mailboxUsageDetailsRequestBuilder = null;
IReportRootGetMailboxUsageDetailRequest mailboxUsageDetailsRequest = null;
mailboxUsageDetailsRequestBuilder = graphServiceClient.Reports.GetMailboxUsageDetail(period);
mailboxUsageDetailsRequest = mailboxUsageDetailsRequestBuilder.Request();
mailboxUsageDetailsReport = await mailboxUsageDetailsRequest.GetAsync();
The last line throws:
Newtonsoft.Json.JsonReaderException
HResult=0x80131500
Message=Unexpected character encountered while parsing value: R. Path '', line 0, position 0.
Source=Newtonsoft.Json
Fiddler shows 302 response with correct file "Location" but body of response contains just a 0,
Work around is
HttpRequestMessage hrm = new HttpRequestMessage(HttpMethod.Get, mailboxUsageDetailsRequest.RequestUrl);
await graphClient.AuthenticationProvider.AuthenticateRequestAsync(hrm);
HttpResponseMessage response = await graphClient.HttpProvider.SendAsync(hrm);
The Microsoft Graph .Net client v1.12.0 does not currently support the Reports API in a first class manner. You are sharing the suggested workaround, we thank you for sharing that. The response is a csv file, that's why you see the JsonReaderException.

How to POST JSON using Adobe Flex

I'm trying to POST some JSON data using Adobe Flex but having some problems. I'm now getting the error message "A URL must be specified with useProxy set to false", even though I do have useProxy set to false.
Update : code below is now working.
var data:Object = new Object();
data.ipaddr = ipaddr.text;
data.netmask = netmask.text;
data.gatewayip = gatewayip.text;
var jsonData:String = JSON.stringify(data);
var s:mx.rpc.http.HTTPService = new mx.rpc.http.HTTPService();
// URL needs to be specified on a separate line, call is unreliable otherwise
s.url = Utils.getBaseURL() + '/cgi-bin/setnetworksettings';
s.contentType = "application/json";
s.resultFormat = mx.rpc.http.HTTPService.RESULT_FORMAT_TEXT;
s.method = "POST";
s.useProxy = false;
s.addEventListener("result", httpResult);
s.addEventListener("fault", httpFault);
s.send(jsonData);
What do you mean by "doesn't seem to do anything"? No response from the server? Fault instead of result? Which one? Help us help you with more details, just stating it doesn't work is not enough.
First of all, be sure that your URL is correct, you should get something in the service result handler OR fault handler, anything. That should help you diagnose and fix any URL problems if any.
Then for the JSON part, you object is not a valid JSON (no escaping and : instead of =), try sending this first: {"ipaddr":"10.1.1.1"}.
From here it should be easy: as F4L stated, you can use the JSON class to encode a real object directly to JSON.
Hope that helps