Best way to know which property has the error deserializing JSON? - json

I am currently getting invlaid JSON back from TFS similar to the following:
{
"value": [
{
"version": 46874,
"changeDate": "2016-10-27T11:18:37.14Z",
"size"/8,
"hashValue": "ADnOi7g3m13IlYXnt9Q5Qw==",
"path": "$/some/random/file",
"url": "https://example.com/blah"
}, //...
],
"count": 14
}
While the TFS admins figure out what is wrong with TFS, I've decided that the, while undesirable, not having the file's size is not crucial to the project and I want to just ignore this error for now.
Google lead me to this question. If I wanted to ignore all errors, this would be fine. I only want to ignore the error for the size property. So I wrote this error handler:
public void HandleDeserializationError(object sender, Newtonsoft.Json.Serialization.ErrorEventArgs errorArgs)
{
if (errorArgs.ErrorContext.Path.EndsWith(".size"))
errorArgs.ErrorContext.Handled = true;
}
Unfortunately, errorArgs.ErrorContext.Path is value[2].changeDate when parsing the line "size"\8,. This seems wrong.
I could store the response in a field before deserialization and then use errorArgs.ErrorContext.Error.LinePosition like so:
public void HandleDeserializationError(object sender, Newtonsoft.Json.Serialization.ErrorEventArgs errorArgs)
{
var pos = (errorArgs.ErrorContext.Error as JsonReaderException)?.LinePosition ?? 0;
if (pos > 6 && _parseData.Substring(pos - 6,6) == "\"size\"")
errorArgs.ErrorContext.Handled = true;
}
This seems awkward though. Does anyone have a better suggestion?

Related

Best Schema for a Data List in JSON for RestFul API to use in Angular

I've been wondering for some days what kind of scheme would be more appropriate to use a data list in json in a web application.
I'm developing a REST Web Application, and im using Angular for front end, i should order, filter and print these data list also in xml ...
For you what scheme is better and why?
1) {
"datas": [
{ "first":"","second":""},
{ "first":"","second":""},
{ "first":"","second":""}
]
}
2) {
"datas": [{
"data": { "first":"","second":""},
"data": { "first":"","second":""},
"data": { "first":"","second":""}
}]
}
3) [
{ "first":"","second":""},
{ "first":"","second":""},
{ "first":"","second":""}
]
Thanks so much.
The first and third notations are quite similar because the third notation is included in your first.
So the question is "Should I return my datas as an array or should I return an object with a property that contain the array ?
It will depend on either you want to have more information alongside your datas or not.
For exemple, if your API might return an error, you will want to manage it from the front end.
In case of error, the JSON will looks like this :
{
"datas": null,
"error": "An error occured because of some reasons..."
}
At the opposite, if everything goes well and your API actually return the results, it will looks like this :
{
"datas": [
{ "first":"","second":""},
{ "first":"","second":""},
{ "first":"","second":""}
],
"error": null
}
Then your front end can use the error property to manage errors sent from the API.
var result = getDatas(); // Load datas from the API
if(result.error){
// Handle the error, display a message to the user, ...
} else {
doSomething(result.datas); // Use your datas
}
If you don't need to have extra properties like error then you can stick with the third schema.
The second notation is invalid. The datas array will contain only one object which will have one property named data. In this case data is a property that is defined multiple times so the object in the array will contain only the last occurence:
var result = {
"datas": [{
"data": { "first":"a","second":"b"},
"data": { "first":"c","second":"d"},
"data": { "first":"e","second":"f"}
}]
}
console.log("Content of result.datas[0].data : ")
console.log(result.datas[0].data)
Obviously the first option would be easy to use. Once you will access datas it'll give you an array. Any operation (filter, sort, print) on that array will be easy in comparison to anything else. Everywhere you just need to pass datas not datas.data.

Error 400/401 trying to create a webhook

I am brand new to webhooks and have had a nightmare trying to get my first one to function. I am trying to use a Particle Photon to send a single float temperature variable to a site that can graph the data. I've tried creating webhooks to thingspeak.com and librato.com with no success. My main attempts have been trying to use the json code in tutorials to create the webhook.
Here is my Photon's code:
#include "Particle.h"
float temp = 70.1000;
float adjust = 0.4;
int acOn = 0;
void setup()
{
}
void loop()
{
if(temp < 72)
adjust = random(1620000)/1000000.0;
else if(temp < 74)
adjust = random(1000000)/1000000.0;
else
adjust = -1*random(500000,2200000)/1000000.0;
temp = temp + adjust;
Particle.publish("librato_", String(temp), 60, PRIVATE);
Particle.process();
delay(30000);
}
and the webhook JSON code (for the librato attempt)
{
"event": "librato_",
"url": "https://metrics-api.librato.com/v1/metrics",
"requestType": "POST",
"auth": {
"username": "YOUR_LIBRATO_USERNAME",
"password": "YOUR_LIBRATO_API_TOKEN"
},
"json": {
"gauges": [
{
"name": "{{NAME}}",
"value": "{{temp}}",
"source": "{{PARTICLE_DEVICE_ID (particle API token?)}}"
}
]
},
"mydevices": true
}
where I have filled in the username and API token found on librato and also the particle api token in the IDE settings. Thanks in advance for the help.
Looks like this user had a similar problem which was solved with a simple renaming or the webhook:
https://community.particle.io/t/connection-to-librato-solved/19230
Check with the Particle CLI if any events are being generated. If you are still not seeing data in Librato, reach out to support#librato.com so that we can check the API for errors.

Json.net JObject.Parse erroring on complex json

The following code:
let resp = string(argv.GetValue 0)
let json =JObject.Parse resp
gives this error:
An unhandled exception of type 'Newtonsoft.Json.JsonReaderException'
occurred in Newtonsoft.Json.dll
Input string '2.2.6' is not a valid number.
Path 'items[0].versionName', line 1, position 39.
where argv is this input:
{
"totalCount":1,
"items":[
{
"versionName":"2.2.6",
"phase":"PLANNING",
"distribution":"EXTERNAL",
"source":"CUSTOM",
"_meta":{
"allow":[
"GET",
"PUT",
"DELETE"
],
"href":"url",
"links":[
{
"rel":"versionReport",
"href":"url"
},
{
"rel":"project",
"href":"url"
},
{
"rel":"policy-status",
"href":"url"
}
]
}
}
]
}
How can I fix this? Is there a simple way to implement a json reader that does not error here?
I also get this error:
An unhandled exception of type 'Newtonsoft.Json.JsonReaderException'
occurred in Newtonsoft.Json.dll
Error parsing undefined value. Path 'items[0].name', line 1, position 28.
With this input:
{
"totalCount":1,
"items":[
{
"name":"uaa",
"projectLevelAdjustments":true,
"source":"CUSTOM",
"_meta":{
"allow":[
"GET",
"PUT",
"DELETE"
],
"href":"url",
"links":[
{
"rel":"versions",
"href":"url"
},
{
"rel":"canonicalVersion",
"href":"url"
}
]
}
}
]
}
I am trying to read in json of many different schemas that I did not make or know. The first error seems to be because it is trying to generate a float from something that should be output as a string. The second sounds like the schema is too complex and a type would be needed to properly parse it using Json.Deserialize but I'm not sure how to do that and it would take too much time as there are too many schemas to make a types for them all. Is there any way around both these things?
In C# you can use dynamic with something like this:
var json = JsonConvert.DeserializeObject(resp)
And then you could access properties with something like: json.totalCount.
In F# land, this question gives some suggestions for how you might deal with dynamic objects. If you use the package FSharp.Interop.Dynamic you can get the value of totalCount in your example with something like this:
let value:obj = json?totalCount?Value
which gives 1L on my computer.

HttpRequest.getString hitting error function even though its succeeding

Wondering if anyone here could help?
Using Polymer Dart I've set up a service to load a Json feed using the following code:
Future loadService(){
return HttpRequest.getString(_serviceURL)
.then(buildView)
.catchError(handleError);
}
When this code executed, it does successfully hit my buildView function, but I'm also getting an error printed out from my handle error function:
void handleError(Error error){
print(error);
}
I have 3 items in my json feed:
[
{
"module": "module-1",
"data": {
"title": "Dynamic Title 1",
"text": "This is the dynamic text for content block 1."
}
},
{
"module": "module-2",
"data": {
"title": "Dynamic Title 2",
"text": "This is the dynamic text for content block 2."
}
},
{
"module": "module-3",
"data": {
"title": "Dynamic Title 3",
"text": "This is the dynamic text for content block 3."
}
}
]
The error I'm getting is: "RangeError: 3".
I can't find a lot of information about what could be causing this. It doesn't seem to be hindering my app, but I would like to clear it up if at all possible. If anyone has any suggestions, I'm all ears.
Thanks!
Edit: as per the suggestion by Günter Zöchbauer
Now I understand the .catchError() function catches errors from the .then() function. I thought it was only going to catch errors around the HttpRequest itself failing.
In buildView I was looping through the json object using a for loop like this:
void buildView(String jsonString){
contentBlocks = JSON.decode(jsonString);
DivElement wrapper = $['content-modules-wrapper'];
for(int i=0; i < contentBlocks.length; i++){
Element element = new Element.tag(contentBlocks[i]['module']);
wrapper.children.add(element);
}
}
Which is wrong, because .length takes the JSON string length (300 something characters) which i think is a bit weird since I've converted it to an object.. anyway, i fixed it by changing the function to this:
void buildView(String jsonString){
contentBlocks = JSON.decode(jsonString);
DivElement wrapper = $['content-modules-wrapper'];
contentBlocks.forEach((block){
Element element = new Element.tag(block['module']);
wrapper.children.add(element);
});
}
Is there a way to get the number of items in a json object like I was trying to do or should you always just loop through it using forEach()?
This error is probably from your buildView. The indexes of the result are from 0 to 2 not from 1 to 3.

Facebook Graph API not returning standard JSON

I am working on an iOS app using the MonoTouch framework. I am using Visual Studio 2010 Professional SP1 with the Xamarin.iOS (v1.3.250) extension. I have been able to open a valid FacebookConnect.FBSession by using the FacebookConnect.FBLoginView with no issues but when I try to make a Graph API request using FacebookConnect.FBRequest I recieve a non-standard JSON style string. When I run following request through the Graph API Explorer:
me?fields=albums.fields(id,name,cover_photo)
I receive the following response:
{
"id": "111111111111111111",
"albums": {
"data": [
{
"id": "111111111111111111",
"name": "Some Album (#1)",
"cover_photo": "111111111111111111",
"created_time": "000-00-00T00:00:00+0000"
},
{
"id": "111111111111111111",
"name": "Some Album (#2)",
"cover_photo": "111111111111111111",
"created_time": "000-00-00T00:00:00+0000"
},
],
"paging": {
"cursors": {
"after": "xxxxxxxx=",
"before": "xxxxxxxx="
}
}
}
}
Now all of this is just fine and is what I expect to receive but when I make the same Graph API request from my app like this:
public static void GetPhotoAlbums(string _userID)
{
// _userID = "me"
mFBRequest = new FBRequest(FBSession.ActiveSession, _userID + "?fields=albums.fields(id,name,cover_photo)");
FBRequestConnection fbRequestConnection = new FBRequestConnection();
fbRequestConnection.AddRequest(mFBRequest, OnPhotoAlbumsReceived);
fbRequestConnection.Start();
}
static void OnPhotoAlbumsReceived(FBRequestConnection _connection, NSObject _result, NSError _error)
{
if (_error == null)
{
Console.WriteLine("FacebookManager.OnPhotoAlbumsReceived() - JSON: " + _result.Description);
object o = JsonConvert.DeserializeObject(_result.Description);
// ...
}
}
I receive this JSON 'like' response:
{
albums = {
data = (
{
"cover_photo" = 111111111111111111;
"created_time" = "000-00-00T00:00:00+0000";
id = 111111111111111111;
name = "Some Album (#1)";
},
{
"cover_photo" = 111111111111111111;
"created_time" = "000-00-00T00:00:00+0000";
id = 111111111111111111;
name = "Some Album (#2)";
},
);
paging = {
cursors = {
after = "xxxxxxxx=";
before = "xxxxxxxx=";
};
};
};
"id": "111111111111111111";
}
I'm not really sure how/why I'm getting a response formatted in a non-standard way but needless to say, I get Newtonsoft.Json.JsonReaderException when attempting to deserialize the data because it does not follow the standard formatting rules (ie, = instead of : to separate key/value pairs, ; instead of , to separate elements of a container, some keys having quotes while others do not, etc...)
I'm pretty new to Facebook and JSON stuff in general and am really at a loss for what is happening to the response string I receive. Any help, feedback, ideas are greatly appreciated. Thanks.
* Solution *
After a bunch of digging around it seems to be that the Graph API response is indeed JSON but it gets converted to an FBGraphObject which holds a NSMutableArray as it the data makes its way through the MonoTouch->.NET bindings so when I pulled _result.Description (equivalent to _result.ToString() it returned me the string representation of that object which happens to look a lot like JSON but is not. After finding all this out (and a lot of runtime experimentation), I was finally able to extract the data into a usable state by doing this:
static void OnPhotoAlbumsReceived(FBRequestConnection _connection, NSObject _result, NSError _error)
{
if (_error == null)
{
NSArray fieldData = (NSArray) _result.ValueForKeyPath(new NSString("albums.data.name"))
string[] names = NSArray.StringArrayFromHandle(fieldData.Handle);
// ...
}
}
Although this works for me, I have a feeling that there is a better or more robust way to get the data I requested, so if any developers out there can offer any additional tips for improving this solution, I would love to hear them.
As stated in Facebook SDK documentation Graph API:
When a request returns a non-JSON response (such as a "true" literal),
that response will be wrapped into a dictionary using this const as
the key. This only applies for very few Graph API prior to v2.1.
So you can check first if result is an NSDictionary, otherwise you can deserialize the JSON data as usual.
Below some obj-c code you can translate into C#/MonoTouch (I don't know the framework, I hope it is helpful).
NSDictionary *dict;
if ([graphResult isKindOfClass:[NSDictionary class]]) {
dict = (NSDictionary *)graphResult;
} else {
NSError *JSONError;
dict = [NSJSONSerialization JSONObjectWithData:graphResult options:NSJSONReadingAllowFragments error:&JSONError];
if (JSONError) {
NSLog(#"Facebook: JSON parse error: %#", JSONError);
// Handle error
}
}