I have a JSONSchema which will have some items . Now the schema/s that define those items need to be referred in the main schema ?
* one schema that you reference:
{
"id": "http://some.where/sub/schema#",
"type": "object",
"properties": {
"p1": {
"type": "integer",
"minimum": 12
}
}
}
--- * the main schema: ----
{
"id": "http://path.to/base/schema#",
"type": "array",
"items": {
"extends": {
"$ref": "http://some.where/sub/schema#/properties/p1"
},
"divisibleBy": 5
}
}
Also note , i will have multiple items in the item . I do not see a way of doing this in the api . Nor does the api allow me to add custom properties . How can i achieve this ? I am using JSON.net.
Since It will be too long for a comment, I'll post it as an answer. But You should work on it to customize according to your needs.
string oneSchema = #"{
""id"": ""http://some.where/sub/schema#"",
""type"": ""object"",
""properties"": {
""p1"": {
""type"": ""integer"",
""minimum"": 12
}
}
} ";
string main = #"
{
""id"": ""http://path.to/base/schema#"",
""type"": ""array"",
""items"": {
""extends"": {
""$ref"": ""http://some.where/sub/schema#/properties/p1""
},
""divisibleBy"": 5
}
}";
var JObjMain = (JObject)JsonConvert.DeserializeObject(main);
var jObjOther = (JObject)JsonConvert.DeserializeObject(oneSchema);
JToken src = JObjMain["items"]["extends"]["$ref"];
JToken reference = jObjOther["id"];
var path = src.ToString().Replace(reference.ToString(), "").Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
JToken j = jObjOther[path[0]];
for(int i=1;i<path.Length;i++)
{
j = j[path[i]];
}
src.Replace(j);
Console.WriteLine(JObjMain);
Related
Here, I am trying to create a JSON using using Newtonsoft.Json; libraries. I came up with a function which partially does my job and when the same function is called, my previous data on the JObject is lost. I am new to this items JProperty, JObject, JArray, JToken however managed to come up with this code.
The parent is initiated in the function itself and when the function is recursively called its initiated and cleaned up again. So I added another JObject head. Making it more complicated.
string statment = "(Entity.Country = 'USA' AND Entity.ShortName = 'Adele' AND (Entity.CIFNumber = '12345' OR Statement.StatementYear = '2015'))";
public static JObject ConvertToJsonObject(string text)
{
JObject parent = new JObject();
string bracketContents = getWhatsInsideBrackets(text);
parent.Add(new JProperty("operator", ReturnOperator(text)));
parent.Add(new JProperty("rules"));
string[] operators = splitWithOperator(bracketContents);
List<JObject> req = new List<JObject>();
for (int i = 0; i < splitWithOperator(bracketContents).Length; i++)
{
if (!checkIfBracketsExists(operators[i].Trim()))
{
req.Add(GetEachCondition(operators, i));
}
else if (checkIfBracketsExists(operators[i]))
{
parent["rules"] = new JArray(ConvertToJsonObject(operators[i]));
head = parent;
parent["rules"] = (ConvertToJsonObject(operators[i]));
}
}
parent["rules"] = new JArray(req);
head["rules"] = parent;
return parent;
}
I am trying to achieve this JSON output: (Only trying to achieve the key, value of DataSetCommonQuery, dont worry about the other keys on the json)
{
"context": {
"wfId": "00000000-0000-0000-0000-000000000000",
"taskId": "00000000-0000-0000-0000-000000000000"
},
"payLoad": {
"DataSetCommonQuery": {
"operator": "AND",
"rules": [
{
"field": "ENTITY.CIFNumber",
"condition": "<>",
"value": "3123"
},
{
"field": "ENTITY.Country",
"condition": "LIKE",
"value": "USA"
},
{
"operator": "OR",
"rules": [
{
"field": "ENTITY.FYEMonth",
"condition": "=",
"value": "May"
},
{
"field": "STATEMENT.ProfitBeforeTax",
"condition": ">=",
"value": 123123
},
{
"field": "STATEMENT.NetSales",
"condition": "<=",
"value": 234234
},
{
"field": "STATEMENT.statementdatekey_",
"condition": "=",
"value": "2019-07-01 12:00:00"
}
]
}
]
},
"PeerType": "DEFAULT",
"Name": "API TEST",
"Description": "API TEST",
"BmkPeerFormatId": "DBBmk",
"OperationType": "Create"
}
}
I get a System.Format exception when trying this:
var jsonString = String.Format( #"{
""searchOptions"": {
""departurePosition"": { ""id"": {0} },
""arrivalPosition"": { ""id"": 376422 },
""travelModes"": [ ""Flight"", ""Train"", ""Bus"" ],
""departureDate"": ""2017-01-15"",
""passengers"": [
{
""age"": 12,
""discountCards"": [ ]
}
],
""userInfo"": {
""identifier"": ""0.jhvlf8amtgk"",
""domain"": "".com"",
""locale"": ""en"",
""currency"": ""EUR""
},
""abTestParameters"": [ ]
}
}", departurePosition);
I need this when sending a post request to a server.
How can I solve this problem ?
It's probably because the use of { and }
To Escape the { and } use {{ and }}
OfirW already shared this,
string.Format() giving “Input string is not in correct format”
If this is just one variable, regular string concatenation will work fine.
var jsonString =
#"{ ""searchOptions"": {
""departurePosition"": { ""id"": " + departurePosition + #"},
""arrivalPosition"": { ""id"": 376422 },
""travelModes"": [ ""Flight"", ""Train"", ""Bus"" ],
""departureDate"": ""2017-01-15"",
""passengers"": [
{
""age"": 12,
""discountCards"": [ ]
}
],
""userInfo"": {
""identifier"": ""0.jhvlf8amtgk"",
""domain"": "".com"",
""locale"": ""en"",
""currency"": ""EUR""
},
""abTestParameters"": [ ]
}
}";
I have JSON Like below
{
"_id": "0FEB6D4B-8DA5-4143-B926-11A7AE4F3B12",
"device": {
"name": "test",
"family": "test"
},
"channels": [
{
"mcl": 33,
"vtype": "FLOAT",
"category": " Current"
},
{
"tag": "OperationMode",
"vtype": "BYTE",
"enums": [
{
"0": "Off"
},
{
"1": "On"
},
{
"2": "ByPass"
}
]
}
]
}
I am using Json.net to deserialize the JSON to C# object. I am not able to manage to convert the enum list. I validated if this is valid JSON. I tried with custom converter & string converter but reader value is null. Any quick help appreciated.
JObject jR = JObject.Parse(YourJsonString);
JArray oR = (JArray)jR["channels"];
JArray jA = (JArray)oR[1]["enums"];
foreach (var item in jA)
{
Dictionary<string,string> enums = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string,string>>(item.ToString());
foreach (var en in enums)
{
Console.WriteLine(en.Value);
}
}
Fiddler: https://dotnetfiddle.net/ziSep1
This is my Data Structure and I'm trying to access it with simpleJason, through unity/c#, I have accidentally gotten the right data here and there, and otherwise gotten completely empty arrays, I'd like to know if my JSON file is improperly setup for my data structure, or if the parser is somehow falling though, or not properly matching what I'm looking for.
JSON File:
{
"categories": [
{
"name" : "entertainment",
"projects": [
{
"name": "Awards",
"description": "Awards Shows",
"credits": [
"Lead Engineer - Dave Jones",
"VFX Supervisor - John Adrian",
"CG Supervisor - Evan Klein"
],
"meta": [
"awards",
"show",
"stars",
"red carpet"
],
"assets": [
{
"name": "Screen Actors Guild Awards",
"filename": "SAG_Awards.mp4",
"icon": "sag.png",
"stereo": false,
"meta": [
"Screen",
"Actors",
"Guild"
]
},
{
"name": "No Awards",
"filename": "No_SAG_Awards.mp4",
"icon": "no_sag.png",
"stereo": false,
"meta": [
"Screen",
"Actors",
"Guild"
]
},
{
"name": "None Awds",
"filename": "None_SAG_Awards.mp4",
"icon": "none_sag.png",
"stereo": false,
"meta": [
"Screen",
"Actors",
"Guild"
]
}
]
}
]
}
]
}
This is the struct :
private struct jsonAsset {
public string category;
public string project;
public string description;
public string[] credits;
public string[] meta;
public string asset;
public FileInfo file;
public FileInfo icon;
public bool stereo;
public bool overUnder;
};
This is the function:
jsonAsset LoadSceneDataFromJSON(FileInfo jsonFile)
{
jsonAsset asset = new jsonAsset();
Debug.Log("Processing : " + jsonFile);
// Parse File for Data
var N = JSON.Parse(File.ReadAllText(jsonFile.FullName));
var cat_arr = N["categories"].AsArray;
asset.category = N["categories"]["name"].Value;
Debug.Log(N["categories"]["projects"]["assets"]["filename"].Value);
foreach (JSONNode n in cat_arr)
{
asset.project = n["name"].Value;
// Credits
var proj_credits = n["credits"].AsArray;
foreach (JSONNode pc in proj_credits)
{
asset.credits[asset.credits.Length] = pc["credits"].Value;
}
// Project Meta
var proj_meta = n["meta"].AsArray;
foreach (JSONNode pm in proj_meta)
{
asset.meta[asset.meta.Length] = pm["meta"].Value;
}
// Project Array
var proj_arr = n["projects"].AsArray;
foreach (JSONNode nn in proj_arr)
{
var asset_arr = nn["assets"].AsArray;
asset.asset = nn["assets"]["name"].Value;
foreach (JSONNode nnn in asset_arr)
{
asset.asset = nnn["name"].Value;
asset.file = new FileInfo(m_dir + nnn["filename"].Value);
asset.icon = new FileInfo(m_dir + nnn["icon"].Value);
var asset_meta = nnn["meta"].AsArray;
foreach (JSONNode am in asset_meta)
{
asset.meta[asset.meta.Length] = am.Value;
}
}
}
}
return asset;
}
You are treating projects as an object instead of an array.
I dont know what JSON library you are using to give you guidance, but something like this will probably work:
N["categories"]["projects"][0]["assets"]["filename"].Value
namespace WebApplication1.Site
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var accessToken = "" // Token
var client = new FacebookClient(accessToken);
dynamic myInfo = client.Get("me/friends", new { fields = "name,id,work" });
foreach (dynamic friend in myInfo)
{
foreach (dynamic work in friend.work ?? new[] { new { employer = new { name = string.Empty }, position = new { name = string.Empty } } })
{
Response.Write("Employer: " + work.employer.name);
}
}
}
}
}
I am getting the following error on line 21. I cannot figure out what is causing it.
'System.Collections.Generic.KeyValuePair' does not contain a definition for 'work'
Sample JSON Return from the Facebook GraphAPI. This is only the first three friends. There are closer to 4000 friends I am parsing, obviously this gives some context for the structure of the data:
{
"data": [
{
"name": "Mia xxx",
"id": "11381",
"work": [
{
"employer": {
"id": "100982923276720",
"name": "New-York Historical Society"
},
"location": {
"id": "108424279189115",
"name": "New York, New York"
}
}
]
},
{
"name": "Leilah xxx",
"id": "1133"
},
{
"name": "xxx,
"id": "1231",
"work": [
{
"employer": {
"id": "104362369673437",
"name": "Bye Bye Liver: The Philadelphia Drinking Play"
},
"location": {
"id": "101881036520836",
"name": "Philadelphia, Pennsylvania"
},
"position": {
"id": "121113421241569",
"name": "Actress/Bartender"
},
"description": "A sketch comedy/improv show every Saturday night at Downey's on South & Front. Come thirsty!",
"start_date": "2011-09"
},
{
"employer": {
"id": "100952634348",
"name": "Act II Playhouse"
},
"location": {
"id": "109249869093538",
"name": "Ambler, Pennsylvania"
},
"position": {
"id": "125578900846788",
"name": "My Fair Lady"
},
"description": "11 actor version of the classic musical.",
"start_date": "0000-00"
},
An alternative to relying on the dynamic is to capture and parse the JSON with JSON.net, it's designed for querying json data and is really much safer than using dynamic
http://json.codeplex.com/
And deserializing into classes:
http://dotnetbyexample.blogspot.ca/2012/02/json-deserialization-with-jsonnet-class.html
Look at this:
Response.Write("Employer: " + myInfo.work.employer.name);
I suspect you meant:
Response.Write("Employer: " + work.employer.name);
Put it this way - if that's not what you meant, what's the purpose of your work variable?