Here is the little snippet:
foreach (KeyValuePair<string, JSchema> pair in dict)
{
JToken token = pair.Value;
string path = token.Path;
...
}
JSchema class v2.0.0.0 contains implicit operator that provides simple conversion of types.
public static implicit operator JToken (
JSchema s
)
JSchema object may contains something like this:
{
"title": "Массив предупреждений",
"type": "array",
"items": {
"title": "Предупреждение",
"type": "object",
"additionalProperties": false,
"properties": {
"id": {
"title": "Уникальный идентификатор предупреждения",
"type": "string"
},
"element": {
"title": "Идентификатор атрибута данных",
"description": "Идентификатор атрибута данных в запросе, с которым связано предупреждение, может отсутствовать, если такая связь не установлена.",
"type": "string"
},
"title": {
"title": "Заголовок или название предупреждения",
"type": "string"
},
"description": {
"title": "Описание или полный текст предупреждения",
"type": "string"
}
},
"required": [
"id",
"title"
]
}
}
But token variable is always {} (empty). What is wrong?
I also thought that the JToken conversion would treat a JSON schema as a JSON object. Since every JSON schema is itself JSON, that usage makes sense to us.
However, the implementation clearly indicates that the conversion to JToken actually creates a new JSON object that is associated with the current schema. Similarly, the conversion from JToken accesses that associated schema.
Personally, I find this use of casts confusing.
We can work around it by re-parsing the schema as plain JSON:
var json = JObject.Parse(schema.ToString());
Related
I don't want to use Microsoft.Hadoop.Avro.
Is there any way to convert JSON data directly to Avro schema in C# and asp.net core API.
Example: Json Data:
{"name":"John", "age":30, "car":null}
Avro Schema:
"name": "MyClass",
"type": "record",
"namespace": "com.acme.avro",
"fields": [
{
"name": "name",
"type": "string"
},
{
"name": "age",
"type": "int"
},
{
"name": "car",
"type": [
"string",
"null"
]
}
]
}```
Is there a way to generate Serialized string of List <object> without any [ ]
we are doing serialization using following code
JsonConvert.SerializeObject(data)
[
{
"SessionId": "6d1ea52b-9f0c-4c32-835d-49e6db22efee",
"ComponentName": "WebRole",
"Message": "X"
},
{
"SessionId": "6d1ea52b-9f0c-4c32-835d-49e6db22efee",
"ComponentName": "WebRole",
"Message": "Y"
},
{
"SessionId": "6d1ea52b-9f0c-4c32-835d-49e6db22efee",
"ComponentName": "WebRole",
"Message": "Z"
},
{
"SessionId": "6d1ea52b-9f0c-4c32-835d-49e6db22efee",
"ComponentName": "WebRole",
"Message": "XY"
},
{
"SessionId": "6d1ea52b-9f0c-4c32-835d-49e6db22efee",
"ComponentName": "WebRole",
"Message": "XYZ",
"Payload": "X>>1"
}
]
Is there a way to remove above [ and ] , I have workaround to call Trim('[') and Trim(']') on serialize string. Is there any setting that come out of box from NewtonSoft which removes [ and ], also I dont want to make use of anonymous object.
No there's no way, if data is a collection then JsonConvert will return a JSON array. You can as you stated modify the output string by using Trim('[').Trim(']') but your JSON won't be valid.
You're trying to use a List, not a Map/Dictionary, but you don't want the array behavior that comes with a List (but not a Dictionary/Map).
Get these straight and you'll find data MUCH easier to work with in many programming languages ;)
https://stackoverflow.com/a/4131714/901899
I want to select objects from a JSON string by filtering using a JSONPath expression with another expression embedded in the filter. In other words, I want to filter for a value that is present elsewhere in the JSON data.
For example:
In the following JSON data there is a value in $.Item.State.stepId (currently "QG2.0"). I need to have a JSONPath expression that selects values based on this value, like this:
$..Step[?(#.stepId==$Item.State.stepId)].actionDate
But this will not return any results. If I use the string ("QG2.0") directly like this:
$..Step[?(#.stepId=='QG2.0')].actionDate
it will return the required data.
What's wrong, or is it not even possible? My JSON is below:
{
"Item": {
"Common": {
"folio": "PSH-000016020",
"setName": "123-XZ200-1",
"wfId": "Kat1_002",
"wfIssue": "002",
"wfIdIssue": "Kat1_002.002"
},
"State": {
"status": "IN WORK",
"stepId": "QG2.0",
"stepDescription": "Validation"
},
"Participants": {
"Participant": [
{
"role": "PR",
"roleDescription": "Product Responsible",
"loginName": "marc102",
"email": "mark#abc.de"
}, {
"role": "CR",
"roleDescription": "Chapter Responsible",
"loginName": "uli26819",
"email": "uli#abc.de"
}
]
},
"Steps": {
"Step": [
{
"stepId": "QG1.0",
"stepTitle": "Preparation",
"actionDate": "2016-06-28T10:28:09",
"actionDueDate": "",
"actionBy_Name": "Marc",
"actionBy_Account": "marc102",
"action": "complete",
"Comment": ""
}, {
"stepId": "QG2.0",
"stepTitle": "Check Requirements",
"actionDate": "2016-08-08T14:17:04",
"actionDueDate": "",
"actionBy_Name": "Uli",
"actionBy_Account": "uli26819",
"action": "complete",
"Comment": ""
}
]
}
}
}
I don't think Json.Net's implementation of JSONPath supports this concept.
However, you can still get the information you want if you break the query into two steps:
JObject obj = JObject.Parse(json);
JToken stepId = obj.SelectToken("Item.State.stepId");
JToken actionDate = obj.SelectToken(string.Format("$..Step[?(#.stepId=='{0}')].actionDate", stepId));
Console.WriteLine(actionDate.ToString());
Fiddle: https://dotnetfiddle.net/KunYTf
I want to extract a JSON schema (as defined here) from an object of type dynamic.
This is the best example I could find.
But JSON.NET's Schema Generator needs to look at an actual class/type to be able to generate a schema.
Anyone have any ideas on how I could extract a schema from a dynamic object?
You can still use JSON.NET to extract a JSON schema from dynamic object. You just need an actual object of type dynamic to be able to do that. Try the following sample:
dynamic person = new
{
Id = 1,
FirstName = "John",
LastName = "Doe"
};
JsonSchemaGenerator schemaGenerator = new JsonSchemaGenerator {};
JsonSchema schema = schemaGenerator.Generate(person.GetType());
The generated JSON schema should look like this:
{
"type": "object",
"additionalProperties": false,
"properties": {
"Id": {
"required": true,
"type": "integer"
},
"FirstName": {
"required": true,
"type": [
"string",
"null"
]
},
"LastName": {
"required": true,
"type": [
"string",
"null"
]
}
}
}
If you are using .NET 4.0+ then there is a method System.Web.Helpers.Json.Decode that converts JSON into a dynamic object:
using System.Web.Helpers;
// convert json to a dynamic object:
var myObject = Json.Decode(json);
// or to go the other way and get json from a dynamic object:
string myJson = Json.Encode(myObject);
To reference this assembly you can find it in the Extensions group under Assemblies in Visual Studio 2012.
This should be able solve your problem. If you can include a sample of the JSON it would be clearer.
I want to deserialize a json that I get as result of a REST query (the json string can not be changed) to a dictionary type.
The json string looks something like this:
{
"collection": {
"useful": true
"attributes": {
"ObjectID": "ObjectID",
"Name": "Name",
"FirstID": "FirstID",
"LastID": "LastID",
"Count": "5",
},
"Type": "Polyline",
"features": [{
"attributes": {
"length": 0.10879009704943393
"time": 0.3822371137674949,
"text": "some text",
"ABC": -2209161600000,
"Type": "SomeType"
}
}]
}
}
I create boolean property for 'useful' and integer for 'count' etc. but I have a problem with the 'attributes'. As you can see, in each section (and per result) I get different 'attributes'.
I need to deserialize them into some generic collection like dictionary or list of KeyValuePair. the problem is, as stated in msdn (here - http://msdn.microsoft.com/en-us/library/bb412170.aspx) "Dictionaries are not a way to work directly with JSON".
How can I do it if so?
My application is silverlight 5, .Net 4, VS 2010.
Thanks in advance!