FormatException (FormatException: Unexpected character (at character 1) - json

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.

Related

API Response returns Mappable Object in iOS but Json on Android

I'm a newbie on mobile development and React-Native, this might come across as a very mundane thing to some of you, but I'm making an Api call and then mapping the results to create the same component but with different data.
This works fine on Iphone but on Android it does not.
The response from the req is an Object for both devices but on Android, it seems to be a json object that I simply cannot map with or use on a Flatlist.
I've tried JSON.parse to get the json object to a js object but it simply doesn't, like it. It throws out an unexpected token error.
I've attached a log for the Android object first and the same object for iPhone (Already mappable and a JS object).
Can someone tell me why this happens? I'd very much appreciate it!
enter image description here
____________________ After Changing to Fetch _______________________
Hey, I changed from Axios to fetch and now I get an unhandled promise warning saying 'Unhandled promise rejection: SyntaxError: JSON Parse error: Unrecognized token '' '.
Don't think I'm doing anything wrong here...
Well ... your response-object gets truncated due to memory issues on your real-device ... most likely your response object is kinda large ...
And that's just the way axios fetch response-data ... through chunks, you just get a slice of the response...
I came across this issue before ... and the solution was to switch to fetch
Edit
try {
const rawResponse = await fetch(...);
const text = await rawResponse.text();
console.log(text);
const parsedRes = JSON.parse(text);
console.log('parsedRes', parsedRes);
} catch(error) {
console.log('fetch error', error);
}

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.

JSON - WepAPI - Unexpected character encountered while parsing value

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

NativeScript Throwing Error Response with status: 200 for URL: null

I am using Angular4 with TypeScript version 2.2.2
My web app is running fine when I call JSON with Filters but my NativeScript app fails when I call the Filter Values as an Object but works fine when I call filter values as a string.
Error Response with status: 200 for URL: null
THIS WORKS
https://domainname.com/api/v1/searchevents?token=057001a78b8a7e5f38aaf8a682c05c414de4eb20&filter=text&search=upcoming
If the filter value and search value is STRING it works whereas if they are objects as below, it does not work
THIS DOES NOT WORK
https://api.domainname.com/api/v1/searchevents?token=057001a78b8a7e5f38aaf8a682c05c414de4eb20&filter={"limit":"12","skip":"0"}&search={"search":"","latitude":"","longitude":"","categories":"","address":"","type":"upcoming"}
The Code I used is below
getData(serverUrl, type, skip_limit) {
console.log(serverUrl);
let headers = this.createRequestHeader();
let token_value = localStorage.getItem('access_token')
let url;
var filter;
filter = '{"limit":"10","skip":"0"}'
url = this.apiUrl + serverUrl + '?token=' + token_value + '&filter=' + filter
return this.http.get(url, { headers: headers })
.map(res => res.json());
}
The URL as formed above for the API is fine and works fine. Yet the error comes Error Response with status: 200 for URL: null
CAN ANYONE HELP ME SOLVE THIS?
Looks like the issue is the "filter" values are of different type and from what you mentioned as what worked, your service is expecting a string and not an object/array. So it fails to send the proper response when it gets one. With an object in the URL, you may have to rewrite the service to read it as an object (parse the two attributes and get them individually)
To make it simple, you can make these two as two different variables in the URL. like below,
https://api.domainName.in/api/v1/oauth/token?limit=10&skip=0
Be more precise in whats happening in your question,
1) Log the exact URL and post it in the question. No one can guess what goes in "text" in your first URL.
2) Your URL which you mentioned as worked have "token" as part of path, but in the code, its a variable which will have a dynamic value from "token_value".
3) Post your service code. Especially the signature and input parsing part.
Got the solution:
All you have to do is encode the Filter and Search Parameters if it is an Object or Array using Typescript encodeURI()
var filter = '{"limit":"12","skip":"0"}'
var search = '{"search":"","latitude":"","longitude":"","categories":"","address":"","type":"upcoming"}'
var encoded_filter = encodeURI(filter);
var encoded_search = encodeURI(search);
url = this.apiUrl+serverUrl+'?token='+token_value+'&filter='+encoded_filter+'&search='+encoded_search