Convert JSON File to JSON Object - c#

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.

Related

Validating JSON with JSON Schema in C# using Newtonsoft

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!

Additional text found, but JSONLint says JSON validated correctly

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).

C# Json File Add New Value

Example:
"database": {
"UUIDTOKEN": {
"name": "test",
"yearsold": "20",
"userid": "100",
"uuid": "a2b45475-aebe-4103-9c01-43ea8754dfc0",
"email": "email#gmail.com"
}
},
How to add new value ? so, database = main json text. How to add uuid {
name,yearsold,userid,uuid,email
}
"database": {
"UUIDTOKEN": {
"name": "test",
"yearsold": "20",
"userid": "100",
"uuid": "a2b45475-aebe-4103-9c01-43ea8754dfc0",
"email": "email#gmail.com"
},
"UUIDTOKEN": {
"name": "stackoverflow",
"yearsold": "24",
"userid": "110",
"uuid": "uuid-aebe-4103-9c01-43ea8754dfc0",
"email": "stackoverflow#gmail.com"
},
},
Thanks for help.
An object (the "database" in your case) can't have two fields with the same name ("UUIDTOKEN"). If you need your "database" to contain a list of "UUIDTOKEN" objects, consider changing it to an array:
{
"database": [{
"name": "test",
"yearsold": "20",
"userid": "100",
"uuid": "a2b45475-aebe-4103-9c01-43ea8754dfc0",
"email": "email#gmail.com"
}, {
"name": "stackoverflow",
"yearsold": "24",
"userid": "110",
"uuid": "uuid-aebe-4103-9c01-43ea8754dfc0",
"email": "stackoverflow#gmail.com"
}]
}
Please note, the "UUIDTOKEN" name was eliminated in this sample, but if you need it for some reason, add another object layer:
{
"database": [{
"UUIDTOKEN": {
"name": "test"
//...
}
}, {
"UUIDTOKEN": {
"name": "stackoverflow"
//...
}
}]
}
I'm not exactly sure what you are asking? Do you want to know how to add another value to a json object in c#, or do you want to know why what you've written won't work?
If it's the latter, you can't have a json object with 2 keys the same, you will need to change UUIDTOKEN to a unique key. Otherwise you could use an array.

Deserialize a JSON Response from OrientDB in CSharp

I started testing OrientDB. I get the following JSON Response from the Demo Database:
{
"schema":{
"name":"OUser",
"properties":{
"roles":{
"name":"roles",
"linkedClass":"ORole",
"type":"LINKSET",
"mandatory":false,
"notNull":true,
"min":null,
"max":null
},
"name":{
"name":"name",
"type":"STRING",
"mandatory":true,
"notNull":false,
"min":null,
"max":null
},
"password":{
"name":"password",
"type":"STRING",
"mandatory":true,
"notNull":false,
"min":null,
"max":null
}
}
},
"result":[
{
"#type":"d",
"#rid":"#4:0",
"#version":0,
"#class":"OUser",
"name":"admin",
"password":"{SHA-256}8C6976E5B5410415BDE908BD4DEE15DFB167A9C873FC4BB8A81F6F2AB448A918",
"status":"ACTIVE",
"roles":[
"#3:0"
]
},
{
"#type":"d",
"#rid":"#4:1",
"#version":0,
"#class":"OUser",
"name":"reader",
"password":"{SHA-256}3D0941964AA3EBDCB00CCEF58B1BB399F9F898465E9886D5AEC7F31090A0FB30",
"status":"ACTIVE",
"roles":[
"#3:1"
]
},
{
"#type":"d",
"#rid":"#4:2",
"#version":0,
"#class":"OUser",
"name":"writer",
"password":"{SHA-256}B93006774CBDD4B299389A03AC3D88C3A76B460D538795BC12718011A909FBA5",
"status":"ACTIVE",
"roles":[
"#3:2"
]
}
]
}
How can you get a List of OUser Objects out of that? Using JSON.Net, JavaScriptSerializer or whatever?
There are a number of json parsers for c# at:
http://www.json.org/. It seems like fastJSON should be pretty quick.
Once logged in execute a query against OUser class:
select from ouser
Via HTTP protocol would be a GET request against this address:
http://localhost:2480/query/demo/sql/select%20from%20ouser
{
"result": [{
"#type": "d", "#rid": "#4:0", "#version": 0, "#class": "OUser",
"name": "admin",
"password": "{SHA-256}8C6976E5B5410415BDE908BD4DEE15DFB167A9C873FC4BB8A81F6F2AB448A918",
"status": "ACTIVE",
"roles": ["#3:0"]
}, {
"#type": "d", "#rid": "#4:1", "#version": 2, "#class": "OUser",
"name": "reader",
"password": "{SHA-256}3D0941964AA3EBDCB00CCEF58B1BB399F9F898465E9886D5AEC7F31090A0FB30",
"status": "ACTIVE",
"roles": ["#3:1"]
}, {
"#type": "d", "#rid": "#4:2", "#version": 0, "#class": "OUser",
"name": "writer",
"password": "{SHA-256}B93006774CBDD4B299389A03AC3D88C3A76B460D538795BC12718011A909FBA5",
"status": "ACTIVE",
"roles": ["#3:2"]
}
]
}
this looks like an easy structure to deserialise using json.NET

Deserialize complex JSON object using ASP.NET?

I've successfully created code that serializes a complex javascript object and posts it to an ASP.NET page. I can get the JSON string using Request.Form and the result looks like this (I've added indentation for readability):
{
"gasterPerStolPerVecka": {
"name": "gasterPerStolPerVecka",
"keyValue_id": "2",
"set_id": "1",
"containerElement": "#gasterPerStolPerVecka",
"keyValueComponents": [
{
"name": "gasterPerStolPerVecka_guestsPerWeek",
"value": "200"
},
{
"name": "gasterPerStolPerVecka_numberOfChairs",
"value": "100"
}
],
"keyValueUnitText": "gäster/stol per vecka",
"keyValueCalculationMethod": "divide",
"isValid": true,
"result": 2
},
"tillgangligaStolstimmarPerVecka": {
"name": "tillgangligaStolstimmarPerVecka",
"keyValue_id": "1",
"set_id": "1",
"containerElement": "#tillgangligaStolstimmarPerVecka",
"keyValueComponents": [
{
"name": "tillgangligaStolstimmarPerVecka_openHoursPerWeek",
"value": "35"
},
{
"name": "tillgangligaStolstimmarPerVecka_numberOfChairs",
"value": "100"
}
],
"keyValueUnitText": "stolstimmar/vecka",
"keyValueCalculationMethod": "multiply",
"isValid": true,
"result": 3500
},
"planeradIntaktPerTillgangligStolOchVecka": {
"name": "planeradIntaktPerTillgangligStolOchVecka",
"keyValue_id": "",
"set_id": "",
"containerElement": "#planeradIntaktPerTillgangligStolOchVecka",
"keyValueComponents": [
{
"name": "planeradIntaktPerTillgangligStolOchVecka_weeklyRevenue",
"value": ""
},
{
"name": "planeradIntaktPerTillgangligStolOchVecka_numberOfChairs",
"value": "100"
}
],
"keyValueUnitText": "kr",
"keyValueCalculationMethod": "divide",
"isValid": false,
"result": null,
"errorText": "Ofullständigt underlag för beräkning."
},
"planeradIntaktPerTillgangligaStolstimmar": {
"name": "planeradIntaktPerTillgangligaStolstimmar",
"keyValue_id": "",
"set_id": "",
"containerElement": "#planeradIntaktPerTillgangligaStolstimmar",
"keyValueComponents": [
{
"name": "planeradIntaktPerTillgangligaStolstimmar_weeklyRevenue",
"value": ""
},
{
"name": "planeradIntaktPerTillgangligaStolstimmar_openHoursPerWeek",
"value": "35"
},
{
"name": "planeradIntaktPerTillgangligaStolstimmar_numberOfChairs",
"value": "100"
}
],
"keyValueUnitText": "kr",
"keyValueCalculationMethod": "divide_divide",
"isValid": false,
"result": null,
"errorText": "Ofullständigt underlag för beräkning."
}
}
Now I try to deserialize this on the server side, but it's difficult. I keep getting the error:
[NullReferenceException: Object reference not set to an instance of an object.]
I don't know where to start looking for errors?
Thanks in advance!
/Thomas Kahn
use stringify instead serialization
You need to use a deserialization library for ASP.NET. See http://json.org/ for libraries that are available or maybe there is one built into ASP.NET. Either way, the code will look like:
String s = getAppropriateFormField();
Object o = JSONLibraryPackage.parse(s);
where obviously you'll have to fill in the blanks for how you get the form field and then what package and method does the parsing.

Categories