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"": [ ]
}
}";
Related
I have a JSON structure that contains different levels. How to iterate the JSON and get all values of a particular key in JSON in C#
Below is my JSON file
{
"name": "EPM Company",
"id": "kpfwzgmhpm",
"type": "root",
"childern": [
{
"cid": "67",
"cname": "cname1",
"childern": [
{
"reading": [
{
"id": 121,
"name": "test1"
},
{
"id": 1121,
"name": "test11"
}
]
}
]
},
{
"cid": "454",
"cname": "cname14",
"childern": [
{
"reading": [
{
"id": 454,
"name": "test14"
},
{
"id": 21,
"name": "test141"
}
]
}
]
}
]
}
This is the JSON format. I am trying to get the value in the below format.
{
"name": "EPM Company",
"id": "kpfwzgmhpm",
"value": [
{
"id": 121,
"name": "test1",
"cid": "67",
"cname": "cname1"
},
{
"id": 1121,
"name": "test11",
"cid": "67",
"cname": "cname1"
},
{
"id": 124234,
"cname": "test12342",
"cid": "67",
"name": "cname1"
},
{
"id": 454,
"name": "test14",
"cid": "454",
"cname": "cname14"
},
{
"id": 21,
"name": "test141",
"cid": "454",
"cname": "cname14"
},
{
"id": 121,
"name": "test123122",
"cid": "454",
"cname": "cname14"
}
]
}
fetching all the reading key and its value-added to array with its cid and came. is it possible?
advanced thanks for the help
my code in c# is
public string SensorList(string entireData)
{
if (string.IsNullOrEmpty(entireData))
{
return string.Empty;
}
var returnObj = new Jobject ();
JObject o = JObject.Parse(entireData);
var childern = o["children"];
returnObj.Add("name" = o ["name"];
returnObj.Add("id" = o ["id"];
returnObj.Add("value" = o ["value"];
var valuearry = new JArray();
foreach(var data in childern)
{
foreach(var reading in data["reading"])
{
var valobj = new Jobject ();
valobj.Add( "cid",data["id"])
valobj.Add( "cname",data["name"])
valobj.Add( "name",reading["id"])
valobj.Add( "id",reading["name"])
valuearry.add()
if(data.containsKey("children"))
{
var sensorInfo = SensorList(data["children"]);
}
}
returnObj.Add("value",valuearry);
// var output = sensorInfo.SelectMany(x => ((JObject)x).Properties().Select(y => new JObject {
// new JProperty("id",y.Name),
// new JProperty("name",y.Value["name"])
// })).ToList();
// var returnArray = new JArray(output);
return returnObj.ToString();
}
}
recurring part is not working and take too much time for other long JSON file
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 am usin NewtonSoft JSON.Net and I have a JObject that I need to add and remove items to and form it dynamicly from my code.
If this is my json:
{
"IgnoredInterests": [
{
"Id": 1,
"Name": "test"
},
{
"Id": 2,
"Name": "test"
}
]
}
I need to be able to add more items or even remove items from it via code.
How can I add this to the JObject:
{
"Id": 3,
"Name": "test"
}
And even remove:
{
"Id": 2,
"Name": "test"
}
I appreciate your help...
string json = #"{
'IgnoredInterests': [
{
'Id': 1,
'Name': 'test'
},
{
'Id': 2,
'Name': 'test'
}
]
}";
JObject obj = JObject.Parse(json);
string json_add = #"{
'Id': 3,
'Name': 'test'
}";
JArray array = obj.GetValue("IgnoredInterests") as JArray;
JObject obj_add = JObject.Parse(json_add);
array.Add(obj_add);
foreach (JObject item in array.Children())
{
if (item.GetValue("Id").ToString() == "2")
{
array.Remove(item);
break;
}
}
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?
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);