Im trying to read some json data using RestSharp.
But im having some problems reading json objects.
I have this respons:
expand: "html",
self: "<url>/INCIDENT-447",
key: "INCIDENT-447",
fields: {
customfield_11414: {
name: "Corrective Measures",
type: "com.atlassian.jira.plugin.system.customfieldtypes:textarea"
},
summary: {
name: "summary",
type: "java.lang.String",
value: "BLA BLA BLA"
},
I need to create a object with Property's summery and customfield_11414
But i only need the value of them. Not the entire JSON object
You can use Json.Net and dynamic keyword together
dynamic dynObj = JsonConvert.DeserializeObject(json);
Console.WriteLine(dynObj.fields.customfield_11414.name + " " +
dynObj.fields.summary.value);
You have a few options. One is to not try and deserialise everything, but rather just make the JSON available for LINQ/XPATH style searching. This is using Json.NET:
var json = " ... "; // your json here
var o = JObject.Parse(json);
var summary = o["summary"];
var customfield_11414 = o.SelectToken("customfield_11414");
These return everything as JToken, which you could cast if needed, or further parse.
Related
I'm trying to define a data structure using JSON and validate the actual data using structure definition with JSON definition. I'm trying this in c#.
for example:
"PlayerScore":{
"fields":[
{
"name":"Runs",
"type":"short",
"isRequired":true
},
{
"name":"Wickets",
"type":"byte",
"isRequired":false
}
]
Above is the definition of the data structure. Below is the actual data.
{
"Runs": 20,
"Wickets": 1
},
{
"Runs": 20
}
I want to validate the data type of "Runs" and "Wickets" only if it is a required field.
Newtonsoft's Json.NET (https://www.nuget.org/packages/Newtonsoft.Json/) supports JSON validation versus its schema. Here is the example from their documentation.
Sample where validation returns true
string schemaJson = #"{
'description': 'A person',
'type': 'object',
'properties':
{
'name': {'type':'string'},
'hobbies': {
'type': 'array',
'items': {'type':'string'}
}
}
}";
JsonSchema schema = JsonSchema.Parse(schemaJson);
JObject person = JObject.Parse(#"{
'name': 'James',
'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS']
}");
bool valid = person.IsValid(schema);
// true
Sample where validation returns false
JsonSchema schema = JsonSchema.Parse(schemaJson);
JObject person = JObject.Parse(#"{
'name': null,
'hobbies': ['Invalid content', 0.123456789]
}");
IList<string> messages;
bool valid = person.IsValid(schema, out messages);
// false
// Invalid type. Expected String but got Null. Line 2, position 21.
// Invalid type. Expected String but got Float. Line 3, position 51.
https://www.newtonsoft.com/json/help/html/JsonSchema.htm
Didn't quite get you but if you are trying to validate a json against a Json Schema. This post might be what u need. Json Schema Validation
Not sure why u wanna go that route though. Would it suffice for you to make a C# model and validate the json against it using data annodations? (assuming its an api) Learn about them here Data Annotations
How to fetch "full_name_ac" in the following JSON :-
{
"rows": 10,
"os": "0",
"page": "1",
"total": "1",
"peoples": {
**"123":** {
"url": "http://google.com",
**"id": "123",**
"fname": "Rob",
"lname": "Tom",
"full_name_ac": "Rob Tom"
}
}
}
I can not create model because model is always going to be changed according to "id".
I am trying something like that but not sure how to get the value of full_name_ac
JObject obj = JObject.Parse(data);
I'd recommend you take a look at using JSONPath(s) and use SelectTokens:
JObject obj = JObject.Parse(data);
var names = obj.SelectTokens("$.peoples.*.full_name_ac");
var allNamesAsCsv = String.Join(",", names.Values<string>());
Of course, if you always know that there will always be just one, you can use SelectToken:
var onlyMatchObject = obj.SelectToken("$.peoples.*.full_name_ac");
var onlyMatch = first.Value<string>();
Use Json.Net. try to use dyanamic
dynamic stuff = JsonConvert.DeserializeObject(YOUR-JSON_STRING);
string name = stuff.peoples.123.full_name_ac;
See this link for more info:Deserialize JSON into C# dynamic object?
model is always going to be changed according to "id".
If your model is always changes then you have create one model which contains id and string. String object is a json string of fields. So that you can check Id and it's model fields. so you can compare that fields with json.
"field" :
{
"id" : 123
"fields" :
{
"fname":"string",
"full_name_ac":"string"
}
}
Create json something like above and include this json in your json. When you deserialize your main json you can compare fields. I thing from above you will get some basic idea.
If your model is dynamic then there is only one option i.e. you have
to create a json something like above which contains fields. So that you can
compare that fields with your actual json value.
Maybe you can use a Regex and some basic text parsing, to identify the "full_name_ac" property, and subtract the value, something like:
// just an example, untested
string jsonText = "{...}";
int startIndex = jsonText.indexOf(#"""full_name_ac"":");
int stopIndex = jsonText.indexOf(startIndex, "}");
string value = jsonText.substring(startIndex, stopIndex);
Fetch the value of required token of the deserialized object (in your case obj.peoples has first token as "123" and first token of "123" is the object which has the required properties) and get the required property i.e. full_name_ac from it.
dynamic obj = JObject.Parse(jsonText);
var value = obj.peoples;
var tokenPeople = ((Newtonsoft.Json.Linq.JContainer)obj.peoples).First.First;
string peopleJson =tokenPeople.ToString();
dynamic people = JObject.Parse(peopleJson);
string full_name_ac = people.full_name_ac;
Following line will help you to get the value of full_name_ac
var full_name_ac = obj.SelectToken("peoples.123.full_name_ac").ToString();
using JObject.Parse(jsonString) AND get First element
// Id is dynamic , so parse and get first element
string dynamicName = (string)JObject.Parse(data)["peoples"].Children().First().Children().First()["full_name_ac"];
I have a JSON like this:
var commpanyTags = "[{\"label\":\"Citizen\",\"category\":\"Companies\"},{\"label\":\"Citi Bank\",\"category\":\"Counterparties\"}]";
Is it possible to convert it to
var commpanyTags = [ { label: "Citizen", category: "Companies" }, { label: "Citi Bank", category: "Counterparties" } ];
If it is possible, how to do that?
JSON.parse (here) will do the job if you are in JavaScript land.
If you are in C#, then consider using JSON.NET to parse the JavaScript into a C# object.
var commpanyTags = jQuery.parseJSON( commpanyTags );
I have a C# class which contains a property of Dictionary
I have a web-page which contains a list of items i need to cast into this dictionary.
My web-site will send the list up to my C# MVC application as JSON and then JsonConvert.Deserialise the JSON into my Dictionary object.
JsonConvert.Deserialise is expecting JSON in the following format:
"MyVariableName":{
"Item 1":true,
"Item 2":true
}
I need to know how i can construct this object in JavaScript.
So far, i have tried this without luck:
var items = [];
var v = $('#Items :input');
$.each(v, function(key, val) {
items.push({
key: val.value,
value: val.checked
});
});
JSON.stringify(v, null, 2);
But this returns a json converted value of:
"MyVariableName": [
{
"key": "Item 1",
"value": true
},
{
"key": "Item 2",
"value": true
}]
Which in turn does not de-serialize to my dictionary.
Thanks
Don't make an array; make an object:
var items = {};
$('#Items :input').each(function(i, val) {
items[val.value] = val.checked;
});
You have to use javascript serialization
One more thing you have different value int key, value pair like string and Boolean type, so you have to use Dictionary type.
And JavaScriptSerializerobject you will get System.Web.Script.Serialization name space of System.Web.Extensions.dll, v4.0.30319 assembly.
var jSerializer = new JavaScriptSerializer();
var newList= jSerializer.Deserialize<Dictionary<string,object>>(newData);
I'm using the JSON library NewtonSoft to generate a JSON string:
JObject out = JObject.FromObject(new
{
typ = "photos"
});
return out.ToString();
Output:
{
"typ": "photos"
}
My question:
Is it possible to get the output in a single line like:
{"typ": "photos"}
You can use the overload of JObject.ToString() which takes Formatting as parameter:
JObject obj = JObject.FromObject(new
{
typ = "photos"
});
return obj.ToString(Formatting.None);
var json = JsonConvert.SerializeObject(new { typ = "photos" }, Formatting.None);
Here's a one-liner to minify JSON that you only have a string for:
var myJson = "{\"type\" :\"photos\" }";
JObject.Parse(myJson).ToString(Newtonsoft.Json.Formatting.None)
Output:
{"type":"photos"}
I'm not sure if this is what you mean, but what I do is this::
string postData = "{\"typ\":\"photos\"}";
EDIT:
After searching I found this on Json.Net:
string json = #"{
CPU: 'Intel',
Drives: [
'DVD read/writer',
'500 gigabyte hard drive'
]
}";
JObject o = JObject.Parse(json);
and maybe you could use the info on this website.
But I'm not sure, if the output will be on one line... Good luck!
If someone here who doesn't want to use any external library in MVC, they can use the inbuilt System.Web.Script.Serialization.JavaScriptSerializer
One liner for that will be:
var JsonString = new JavaScriptSerializer().Serialize(new { typ = "photos" });