On rare occasion when receiving the message "Additional text found in JSON string after finishing deserializing object." the first thing i do is fix some JSON structure typo of mine using JSONLint.
However this time the lint says the json is valid and i can't see where the problem lies. (As i don't control the data's source i need to ldeserialize to a generic object that i then traverse. - Is this possibly the error on my part?)
I'm deserializing with Unity specific Newtonsoft.Json (JsonNet-Lite)
object resultData = JsonConvert.DeserializeObject<object>(jsonString);
What am i missing?
JSON String
"{\"statements\":[{\"id\":\"14b6382c-ddb9-44c5-a22c-a133cec50711\",\"actor\":{\"objectType\":\"Agent\",\"mbox_sha1sum\":\"f7f99253cf6ede467c3a5425d05bfcd96e524595\",\"name\":\"My Name\"},\"verb\":{\"id\":\"https://w3id.org/xapi/dod-isd/verbs/completed\",\"display\":{\"en-US\":\"completed\"}},\"result\":{\"success\":true,\"completion\":true,\"duration\":\"PT0.05S\"},\"context\":{\"contextActivities\":{\"grouping\":[{\"id\":\"http://example.com/activities/MyActivity_Grandparent\",\"objectType\":\"Activity\"}],\"parent\":[{\"id\":\"http://example.com/activities/MyActivity_Parent\",\"objectType\":\"Activity\"}]}},\"timestamp\":\"2018-02-23T19:18:34.145Z\",\"stored\":\"2018-02-23T19:18:34.145Z\",\"authority\":{\"objectType\":\"Agent\",\"account\":{\"homePage\":\"http://cloud.scorm.com\",\"name\":\"abcdef-ghijk\"},\"name\":\"Test Provider\"},\"version\":\"1.0.0\",\"object\":{\"id\":\"http://example.com/activities/MyActivity\",\"definition\":{\"extensions\":{\"https://w3id.org/xapi/dod-isd/extensions/interactivity-level\":\"3\",\"https://w3id.org/xapi/dod-isd/extensions/ksa\":\"Attitude\",\"https://w3id.org/xapi/dod-isd/extensions/category\":\"Responding\",\"http://example.com/TerminalObjective\":\"My Activity Objective\"},\"name\":{\"en-US\":\"My Activity Name\"},\"description\":{\"en-US\":\"My Activity Description\"},\"type\":\"http://adlnet.gov/expapi/activities/simulation\"},\"objectType\":\"Activity\"}}],\"more\":\"/tc/Z5R2XATQZW/sandbox/statements?continueToken=e50555fe-0c3d-4663-91c4-7f0ff7df4ccf\"}"
JSON Formatted for readability
{
"statements": [{
"id": "14b6382c-ddb9-44c5-a22c-a133cec50711",
"actor": {
"objectType": "Agent",
"mbox_sha1sum": "f7f99253cf6ede467c3a5425d05bfcd96e524595",
"name": "My Name"
},
"verb": {
"id": "https://w3id.org/xapi/dod-isd/verbs/completed",
"display": {
"en-US": "completed"
}
},
"result": {
"success": true,
"completion": true,
"duration": "PT0.05S"
},
"context": {
"contextActivities": {
"grouping": [{
"id": "http://example.com/activities/MyActivity_Grandparent",
"objectType": "Activity"
}],
"parent": [{
"id": "http://example.com/activities/MyActivity_Parent",
"objectType": "Activity"
}]
}
},
"timestamp": "2018-02-23T19:18:34.145Z",
"stored": "2018-02-23T19:18:34.145Z",
"authority": {
"objectType": "Agent",
"account": {
"homePage": "http://cloud.scorm.com",
"name": "abcdef-ghijk"
},
"name": "Test Provider"
},
"version": "1.0.0",
"object": {
"id": "http://example.com/activities/MyActivity",
"definition": {
"extensions": {
"https://w3id.org/xapi/dod-isd/extensions/interactivity-level": "3",
"https://w3id.org/xapi/dod-isd/extensions/ksa": "Attitude",
"https://w3id.org/xapi/dod-isd/extensions/category": "Responding",
"http://example.com/TerminalObjective": "My Activity Objective"
},
"name": {
"en-US": "My Activity Name"
},
"description": {
"en-US": "My Activity Description"
},
"type": "http://adlnet.gov/expapi/activities/simulation"
},
"objectType": "Activity"
}
}],
"more": "/tc/Z5R2XATQZW/sandbox/statements?continueToken=e50555fe-0c3d-4663-91c4-7f0ff7df4ccf"
}
The deserialization method, you chose, is rather for a case, when you are deserializing a well-known Json to an object, which matches the structure.
In this case the Json structure does not match the System.Object type structure, you are trying to deserialize to. The library complaints, that there's much more in the Json, than in the System.Object structure.
For parsing any Json object, you could try an example from the Newtonsoft.Json documentation:
string json = #"{
CPU: 'Intel',
Drives: [
'DVD read/writer',
'500 gigabyte hard drive'
]
}";
JObject o = JObject.Parse(json);
You will still need to traverse the deserialized object. Depending on what you want to achieve, it may actually be much better to look for a .Net class that matches the Json structure (or write one).
Related
With this code:
var button = Value.ForStruct(new Struct{
Fields={
["type"] = Value.ForString("postback"),
["title"] = Value.ForString("Call Representative"),
["payload"] = Value.ForString("+15105551234"),
}
});
var inPayload = Value.ForStruct(new Struct{
Fields ={
["buttons"] = Value.ForList(button),
["text"] = Value.ForString("try the postback"),
["template_type"] = Value.ForString("button"),
}
});
var attachment = Value.ForStruct(new Struct{
Fields ={
["payload"] = inPayload,
["type"] = Value.ForString("template"),
}
});
var msg = Value.ForStruct(new Struct{
Fields ={
["attachment"] = attachment,
});
Payload = new Struct{
Fields ={
["facebook"] = msg
}
I was able to create the following json:
"payload": {
"facebook": {"attachment": {
"payload": {
"buttons": [ {
"type": "postback",
"title": "Call Representative",
"payload": "+15105551234"
}],
"text": "try the postback",
"template_type": "button"
},
"type": "template"
}}
Now I need to create the following other format but I dont find how to do it:
"payload": {
"message": "Yes I did it"
"platform": "kommunicate",
"attachment": {
"payload": {
"buttons": [ {
"type": "postback",
"title": "Call Representative",
"payload": "+15105551234"
}],
"text": "try the postback",
"template_type": "button"
},
"type": "template"
}
I really dont find how to eliminate the first "facebook": { element and leave only:
{
"message": "Yes I did it",
"platform": "kommunicate",
"attachment":
And include message and platform at the same level. Here is the complete json I will like to generate:
"payload": {
"platform": "kommunicate",
"message": "Yes I did it",
"attachment": {
"payload": {
"buttons": [ {
"type": "postback",
"title": "Call Representative",
"payload": "+15105551234"
}],
"text": "try the postbackggggggg",
"template_type": "button"
},
"type": "template"
}
If you want to take an object and convert it to json I would recommend taking a look at Newtonsoft Json.Net library. They have plenty of examples that might help you. There is also protobuf.net library for serializing to protobuf instead of json.
Both libraries are used in similar ways, you create a class with appropriate properties and set the values you want. You will need multiple classes for nested types as in your example. Protobuf requires you to annotate the properties with attributes, while this is optional for json.net. You then send the object to the serialization library and get a string or binary data representing your object. This kind of object is often called a Data Transfer Object (DTO), since the only purpose it has is to aid in serialization or/and transfering the data to another system.
Validate the JSON with JSON Schema return always true.
Newtonsoft is used for validation and tested here with schema and data.
It return always 'No errors found. JSON validates against the schema'.
Please find my JSON Schema.
{
"schema": {
"definitions": {
},
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "http://example.com/root.json",
"type": "object",
"widget": { "formlyConfig": { "type": "accordion" } },
"title": "The Root Schema",
"required": [
"accordion1",
"accordion2",
"accordion3"
],
"properties": {
"accordion1": {
"$id": "#/properties/accordion1",
"type": "object",
"title": "The Accordion1 Schema",
"required": [
"firstname",
"age"
],
"properties": {
"firstname": {
"$id": "#/properties/accordion1/properties/firstname",
"type": "string",
"title": "The Firstname Schema",
"default": "firstname pvr1"
},
"age": {
"$id": "#/properties/accordion1/properties/age",
"type": "integer",
"title": "The Age Schema",
"default": 21
}
}
},
"accordion2": {
"$id": "#/properties/accordion2",
"type": "object",
"title": "The Accordion2 Schema",
"required": [
"firstname",
"age"
],
"properties": {
"firstname": {
"$id": "#/properties/accordion2/properties/firstname",
"type": "string",
"title": "The Firstname Schema",
"default": "firstName2"
},
"age": {
"$id": "#/properties/accordion2/properties/age",
"type": "integer",
"title": "The Age Schema",
"default": 31
}
}
},
"accordion3": {
"$id": "#/properties/accordion3",
"type": "object",
"title": "The Accordion3 Schema",
"required": [
"firstname",
"age"
],
"properties": {
"firstname": {
"$id": "#/properties/accordion3/properties/firstname",
"type": "string",
"title": "The Firstname Schema",
"default": "firstnaem3"
},
"age": {
"$id": "#/properties/accordion3/properties/age",
"type": "integer",
"title": "The Age Schema",
"default": 10
}
}
}
},
'additionalProperties': false
}
}
Please find JSON
{
"accordion1":{
"firstname":"JSON ACCORD PALANIVELRAJAN",
"age":29
},
"accordion2":{
"firstname":"JSON ACCORD LAKSHMANAN",
"age":39
},
"accordion3":{
"firstname":null,
"age":49
}
}
I tried to change the first name to integer and remove the first in accordion1. It return true for all cases.
Please advise.
Please find the code which validate the JSON with JSON Schema.
model is a JObject and it is a valid JSON.
JsonSchema json_schema = JsonSchema.Parse(schema);
IList<string> messages;
bool valid = model.IsValid(json_schema, out messages);
return valid;
JsonSchema is deprecated, and has moved to a separate package: Newtonsoft.Json.Schema. Using this package, I was able to validate your JSON against your schema (I did remove the outer schema element, as it is actually invalid, and causes schema to not validate properly - I think you might've had it in there because the old JsonSchema class could not parse the schema otherwise!), and get error messages if I changed the JSON to an invalid shape, removed required elements, or changed data to invalid types:
string data = File.ReadAllText("data.json");
string schema = File.ReadAllText("data.schema.json");
var model = JObject.Parse(data);
var json_schema = JSchema.Parse(schema);
IList<string> messages;
bool valid = model.IsValid(json_schema, out messages); // properly validates
I am using .NET Core 2.2, Newtonsoft.Json 12.0.2, and Newtonsoft.Json.Schema 3.0.11, just in case it matters. Please note, the Newtonsoft.Json.Schema package has limitations for commercial use - check licensing!
My query goes like this: If I have a feedItem (an image posted on facebook), how can I verify that I have liked it or not? Can I verify all the interactions which I have done to the feedItem or the interactions other people have done to it (like, dislike, pin, share)? Is there any way in getstream.io to retrieve these interactions?
Thanks in advance...
Graph API provides all functions you need. Here are some examples:
Read shares[it's a field of an object]: https://developers.facebook.com/docs/graph-api/reference/v3.1/post#read
Read Shared posts: https://developers.facebook.com/docs/graph-api/reference/v3.1/object/sharedposts
read likes:
https://developers.facebook.com/docs/graph-api/reference/v3.1/object/likes#read
/likes returns only the profile for the current user if read with a
user access token:
Album, Photo, Post, Video
all returns are JSON, which you can directly Deserialize Anonymous Type without using stream, for example, likes:
{
"likes": {
"data": [
{
"name": "Bill the Cat",
"id": "155111347875779",
"created_time": "2017-06-18T18:21:04+0000"
},
{
"name": "Calvin and Hobbes",
"id": "257573197608192",
"created_time": "2017-06-18T18:21:02+0000"
},
{
"name": "Berkeley Breathed's Bloom County",
"id": "108793262484769",
"created_time": "2017-06-18T18:20:58+0000"
}
],
"paging": {
"cursors": {
"before": "Nzc0Njg0MTQ3OAZDZD",
"after": "NTcxODc1ODk2NgZDZD"
},
"next": "https://graph.facebook.com/vX.X/me/likes?access_token=user-access-token&pretty=0&summary=true&limit=25&after=NTcxODc1ODk2NgZDZD"
},
"summary": {
"total_count": 136
}
},
"id": "user-id"
}
I have a JSON file like below and I want to desterilize it to JSON Object how can I do it ? Thanks
{
"TOTAL": 2,
"PRODUCTS": [
{
"CODE": "T55",
"PRICE": 59.95,
"DESCRIPTION": "Ok"
},
{
"CODE": "T75",
"PRICE": 99.95,
"DESCRIPTION": "Not OK"
}]
You can refer this link for parsing from a file :
Get a JSON file from URL and display
And
You can use :
var obj = JSON.parse('{ "name":"Pawan", "age":24}');
Modern browsers support JSON.parse().
var json = [{
"TOTAL": 2,
"PRODUCTS": [
{
"CODE": "T55",
"PRICE": 59.95,
"DESCRIPTION": "Ok"
},
{
"CODE": "T75",
"PRICE": 99.95,
"DESCRIPTION": "Not OK"
}];
var arr_from_json = JSON.parse( json_string );
In browsers that don't, you can include the json2 library.
I've tried 3 different JSON class generators, but I get an error when I try to generate a C# class from the following JSON output:
{
"status": "REQUEST_STATUS",
"language": "DOCUMENT_LANGUAGE",
"url": "REQUESTED_URL",
"text": "DOCUMENT_TEXT",
"entities": [
"entity": {
"type": "DETECTED_TYPE",
"relevance": "DETECTED_RELEVANCE",
"count": "DETECTED_COUNT",
"text": "DETECTED_ENTITY"
"disambiguated": {
"name": "DISAMBIGUATED_ENTITY",
"subType": "ENTITY_SUBTYPE",
"website": "WEBSITE",
"geo": "LATITUDE LONGITUDE",
"dbpedia": "LINKED_DATA_DBPEDIA",
"yago": "LINKED_DATA_YAGO",
"opencyc": "LINKED_DATA_OPENCYC",
"umbel": "LINKED_DATA_UMBEL",
"freebase": "LINKED_DATA_FREEBASE",
"ciaFactbook": "LINKED_DATA_FACTBOOK",
"census": "LINKED_DATA_CENSUS",
"geonames": "LINKED_DATA_GEONAMES",
"musicBrainz": "LINKED_DATA_MUSICBRAINZ",
"crunchbase": "CRUNCHBASE_WEB_LINK",
},
"quotations": [
{
"quotation": "ENTITY_QUOTATION"
}
],
"sentiment": {
"type": "SENTIMENT_LABEL",
"score": "SENTIMENT_SCORE",
"mixed": "SENTIMENT_MIXED"
}
}
]
}
The error is on the following line, at the bracket:
"entities": [
But all the examples I have found using the above two tools do have examples of using arrays like mine, so why does mine cause an exception. The exception is, "Invalid character and line 7 position 17.
If I change the straight brackets to currly brackets it will generate but that's changing the class, right?
things inside of arrays dont themselves have names so just change
"entities": [
"entity": {
"type": "DETECTED_TYPE",
to
"entities": [ {
"type": "DETECTED_TYPE",