Hi I try to get json data inside of the json. But my class is Employee my service creates json as com.myteam.rbffiyatlama2.Employee this prefix can be changeable so I have to write a solution to get an exact part of the json Like below but my below code is not working. I will send my node name to a method Getjsonobject(Employee emp) or Getjsonobject(Customer cust) or Getjsonobject(Student student) etc.
My Json:
{
"type": "SUCCESS",
"msg": "Container RBFFiyatlama2_1.0.1 successfully called.",
"result": {"execution-results": {
"results": [
{
"value": 2,
"key": ""
},
{
"value": {"com.myteam.rbffiyatlama2.Employee": {
"salary": 2400,
"age": 35,
"cofactor": 0.2
}},
"key": "t1"
},
{
"value": {"com.myteam.rbffiyatlama2.Employee": {
"salary": 4800,
"age": 35,
"cofactor": 0.2
}},
"key": "t2"
}
],
"facts": [
{
"value": {"org.drools.core.common.DefaultFactHandle": {"external-form": "0:50:1980606587:1980606587:100:DEFAULT:NON_TRAIT:com.myteam.rbffiyatlama2.Employee"}},
"key": "t1"
},
{
"value": {"org.drools.core.common.DefaultFactHandle": {"external-form": "0:51:2052360932:2052360932:99:DEFAULT:NON_TRAIT:com.myteam.rbffiyatlama2.Employee"}},
"key": "t2"
}
]
}}
}
class Program
{
static void Main(string[] args)
{
var employee1 = new Employee() { age = 35, cofactor = 0.2, salary = 2000 };
var employee2 = new Employee() { age = 35, cofactor = 0.2, salary = 4000 };
var list = new List<Employee>();
list.Add(employee1);
list.Add(employee2);
var uri = new Uri("http://localhost:8080/kie-server/services/rest/server/containers/instances/RBFFiyatlama2_1.0.1");
var kieclient = new KieRequestWrapper<Employee>(uri, "kieserver", "#test2018", MethodType.POST, "application/json").Add(list).Run();
Console.Write(kieclient.Content);
var match = Regex.Match(kieclient.Content, #"(?*.Employee{*})");
var result= MyParser.Parse(match, typeof(Employee)); //Desired
Console.Read();
}
}
public class Employee
{
public int age { get; set; }
public double cofactor { get; set; }
public int salary { get; set; }
}
You don't want to use XPath to get the data you need, you want to deserialize the the JSON string into an object and then get the data you need. There are many JSON serialization libraries out there, the most common one, AFAIK, is JSON.NET. You can look at how deserialization works here: https://www.newtonsoft.com/json/help/html/DeserializeObject.htm
Example:
public class Account
{
public string Email { get; set; }
public bool Active { get; set; }
public DateTime CreatedDate { get; set; }
public IList<string> Roles { get; set; }
}
string json = #"{
'Email': 'james#example.com',
'Active': true,
'CreatedDate': '2013-01-20T00:00:00Z',
'Roles': [
'User',
'Admin'
]
}";
Account account = JsonConvert.DeserializeObject<Account>(json);
Console.WriteLine(account.Email);
// james#example.com
Related
{
"name": "Not Okay Bears Solana #1",
"image": "ipfs://QmV7QPwmfc6iFXw2anb9oPZbkFR75zrtw6exd8LherHgvU/1.png",
"attributes": [
{
"trait_type": "Background",
"value": "Amethyst"
},
{
"trait_type": "Fur",
"value": "Warm Ivory"
},
{
"trait_type": "Mouth",
"value": "Clean Smile"
},
{
"trait_type": "Eyes",
"value": "Not Okay"
},
{
"trait_type": "Hat",
"value": "Bucket Hat"
},
{
"trait_type": "Clothes",
"value": "Plaid Jacket"
},
{
"trait_type": "Eyewear",
"value": "Plastic Glasses"
}
],
"description": "Not Okay Bears Solana is an NFT project for mental health awareness. 10k collection on the Polygon blockchain. We are not okay."
}
I need to add an object to attributes.
How to do this?
My JSON classes:
public class Attribute
{
public string trait_type { get; set; }
public string value { get; set; }
}
public class Root
{
public string name { get; set; }
public string image { get; set; }
public List<Attribute> attributes { get; set; }
public string description { get; set; }
}
try this, in this case you don't need any classes
var jsonObject = JObject.Parse(json);
JObject obj = new JObject();
obj.Add("trait_type", "type");
obj.Add("value", "value");
((JArray)jsonObject["attributes"]).Add(obj);
var newJson=jsonObject.ToString();
but if you need the data not a json , you can use this code
Root data = JsonConvert.DeserializeObject<Root>(json);
data.attributes.Add(new Attribute { trait_type="type", value="value"});
I am try to create a wild card search feature.
I have a json response it contains the username. i have to search the user like te*, so it will display corresponding usernames.
LIke test1, test2
The below code i am using to get the response
var JSONResponse = await SendGraphRequest("/users/", null, null, HttpMethod.Get);
i have tried below code and trying to filter in graph only
i have try to filter in graph only
var JSON = await SendGraphRequest("/users/", $"$filter=startswith(givenname,'b')", null, HttpMethod.Get);
var graphUserResponse2 = JsonConvert.DeserializeObject<GraphUserResponseMapping>(JSON);
so instead of given name i want to try to filter using user name.
i am using newtonsoft to parse the json but it is difficult to get the username in list then then i will apply the wild card search. but the problem is how to get the username and store in a list?
The below is json response
{
"odata.metadata": "test",
"odata.nextLink":"test",
"value": [
{
"odata.type": "Microsoft.DirectoryServices.User",
"objectType": "User",
"signInNames": [
{
"type": "emailAddress",
"value": "test1#gmail"
},
{
"type": "username",
"value": "Test1"
}
],
"personId": "1"
},
{
"odata.type": "Microsoft.DirectoryServices.User",
"objectType": "User",
"signInNames": [
{
"type": "emailAddress",
"value": "test2#gmail.com"
},
{
"type": "username",
"value": "Test2"
}
],
"personId": "2"
}
]
}
TIA
Roger!
You can use a Class ex:
YourClassName.cs
code inside this class
public class SignInName
{
public string Type { get; set; }
public string Value { get; set; }
}
public class Value
{
[JsonProperty(PropertyName = "odata.type")]
public string OdataType { get; set; }
public string ObjectType { get; set; }
public List<SignInName> SignInNames { get; set; }
public string PersonId { get; set; }
}
public class YourClassName
{
[JsonProperty(PropertyName = "odata.metadata")]
public string OdataMetadata { get; set; }
[JsonProperty(PropertyName = "odata.nextLink")]
public string OdataNextLink { get; set; }
public List<Value> Value { get; set; }
}
So you can search for the usernames and put it into a list.
Ex:
List<string> userNameList = new List<string>();
var json = "{ \"odata.metadata\": \"test\", \"odata.nextLink\":\"test\", \"value\": [ { \"odata.type\": \"Microsoft.DirectoryServices.User\", \"objectType\": \"User\", \"signInNames\": [ { \"type\": \"emailAddress\", \"value\": \"test1#gmail\" }, { \"type\": \"username\", \"value\": \"Test1\" } ], \"personId\": \"1\" }, { \"odata.type\": \"Microsoft.DirectoryServices.User\", \"objectType\": \"User\", \"signInNames\": [ { \"type\": \"emailAddress\", \"value\": \"test2#gmail.com\" }, { \"type\": \"username\", \"value\": \"Test2\" } ], \"personId\": \"2\" } ] }";
var yourClassName = JsonConvert.DeserializeObject<YourClassName>(json);
foreach (var value in yourClassName.Value)
{
userNameList.AddRange(value.SignInNames.Where(x => x.Type == "username").Select(x => x.Value).ToList());
}
Get Method is not working... below code display all names or other attributes in richtext box from json using restsharp...there is no error but Ouput is not came help me to solve this...
var client = new RestClient("http://www.jsongenerator.com/api/json/get/cfBwXjwjci?indent=2");
var request = new RestRequest(Method.GET);
var queryResult = client.Execute<List<Detail>>(request).Data;
foreach (var rl in queryResult)
{
richTextBox1.Text = rl.name;
}
public class Detail
{
public string city { get; set; }
public int id { get; set; }
public string Blood { get; set; }
public string name { get; set; }
}
Here is json
{
"Details": [
{
"city": "Londan",
"id": 1,
"Blood": "O+",
"name": "Nicolas"
},
{
"city": "USA",
"id": 2,
"Blood": "A+",
"name": "Jhon"
},
{
"city": "India",
"id": 3,
"Blood": "B-",
"name": "Shiva"
}
]
}
I see two problems:
1) "http://www.jsongenerator.com/api/json/get/cfBwXjwjci?indent=2" - doesn't work
2) If you provided a correct JSON example then you should use "RootObject" here:
client.Execute<List<Detail>>(request).Data;
How do I create a JSON array using Newtonsoft.JSON (json.net) from this json string
[
{
"Cells": {
"results": [
{
"Key": "Title",
"Value": "hello",
"ValueType": "Edm.String"
},
{
"Key": "Size",
"Value": "54549",
"ValueType": "Edm.Int64"
},
{
"Key": "Path",
"Value": "http://somesite/a/hello.pptx",
"ValueType": "Edm.String"
},
{
"Key": "Summary",
"Value": "Some summary <ddd/> interesting reading <ddd/> nice book <ddd/> ",
"ValueType": "Edm.String"
},
{
"Key": "Name",
"Value": "http://somesite",
"ValueType": "Edm.String"
}
]
}
},
{
"Cells": {
"results": [
{
"Key": "Title",
"Value": "hi joe",
"ValueType": "Edm.String"
},
{
"Key": "Size",
"Value": "41234",
"ValueType": "Edm.Int64"
},
{
"Key": "Path",
"Value": "http://someothersite/interesting/hi.pptx",
"ValueType": "Edm.String"
},
{
"Key": "Summary",
"Value": "Some summary <ddd/> interesting reading <ddd/> nice book <ddd/> ",
"ValueType": "Edm.String"
},
{
"Key": "Name",
"Value": "http://somesite",
"ValueType": "Edm.String"
}
]
}
}
]
json2csharp gives me following classes for this structure
public class Result
{
public string Key { get; set; }
public string Value { get; set; }
public string ValueType { get; set; }
}
public class Cells
{
public List<Result> results { get; set; }
}
public class RootObject
{
public Cells Cells { get; set; }
}
How do I use these classes to create json array?
UPDATE AND SOLUTION
this will work
static void Main(string[] args)
{
RootObject ro = new RootObject();
Cells cs = new Cells();
cs.results = new List<Result>();
Result rt = new Result();
rt.Key = "Title";
rt.Value = "hello";
rt.ValueType = "Edm.String";
cs.results.Add(rt);
Result rs = new Result();
rs.Key = "Size";
rs.Value = "3223";
rs.ValueType = "Edm.Int64";
cs.results.Add(rs);
ro.Cells = cs;
string json = JsonConvert.SerializeObject(ro);
}
this will work
static void Main(string[] args)
{
RootObject ro = new RootObject();
Cells cs = new Cells();
cs.results = new List<Result>();
Result rt = new Result();
rt.Key = "Title";
rt.Value = "hello";
rt.ValueType = "Edm.String";
cs.results.Add(rt);
Result rs = new Result();
rs.Key = "Size";
rs.Value = "3223";
rs.ValueType = "Edm.Int64";
cs.results.Add(rs);
ro.Cells = cs;
string json = JsonConvert.SerializeObject(ro);
}
You're looking for the function DeserializeObject<T>:
var json = ""; // string up above in your code
var jObect = JsonConvert.DeserializeObject<RootObject>(json);
// Use
var cells = jObject.Cells;
var result1 = cells.results.FirstOrDefault();
Given an example of a POCO below:
public class Account
{
public string Email { get; set; }
public bool Active { get; set; }
public DateTime CreatedDate { get; set; }
public IList<string> Roles { get; set; }
}
This can be achieved by deserializing your JSON string show below:
string json = #"{
'Email': 'james#example.com',
'Active': true,
'CreatedDate': '2013-01-20T00:00:00Z',
'Roles': [
'User',
'Admin'
]
}";
Account account = JsonConvert.DeserializeObject<Account>(json);
Console.WriteLine(account.Email);
Reference Newtonsoft's documentation below:
http://www.newtonsoft.com/json/help/html/DeserializeObject.htm
If you want the string representation of an object, especially a json object, the most relevant is .ToString ().
But, it could fail for other reasons ...
It gives me error when deserializing this JSON File
{
"checkOut": "10:30",
"stars": 4,
"locationId": 953,
"propertyType": 6,
"checkIn": "15:00",
"trustyou": {
"languageSplit": [
{
"tripTypeSplit": [
{
"type": "family",
"percentage": 85
},
{
"type": "couple",
"percentage": 15
}
],
"name": "de",
"percentage": 100
}
],
"location": [
],
"reviewsCount": 83,
"popularity": 0,
"tripTypeSplit": [
{
"type": "family",
"percentage": 86
},
{
"type": "couple",
"percentage": 14
}
],
"sentimentScoreList": [
{
"categoryId": "14",
"ratio": "Good",
"shortText": "Great location",
"name": "Location",
"subcategories": [
],
"highlights": [
{
"text": "Beautiful location",
"confidence": 100
}
],
"reviewCount": 14,
"score": 100
},
{
"categoryId": "111",
"ratio": "Good",
"shortText": "Rather comfortable",
"name": "Comfort",
"subcategories": [
],
"highlights": [
],
"reviewCount": 5,
"score": 100
},
I have the following classes for this JSON
public class Root
{
[JsonProperty("checkIn")]
public string CheckIn { get; set; }
[JsonProperty("distance")]
public double Distance { get; set; }
[JsonProperty("hidden")]
public bool Hidden { get; set; }
[JsonProperty("trustyou")]
public Trustyou Trustyou { get; set; }
[JsonProperty("amenitiesV2")]
public AmenitiesV2 AmenitiesV2 { get; set; }
[JsonProperty("hasAirbnb")]
public bool HasAirbnb { get; set; }
[JsonProperty("checkOut")]
public string CheckOut { get; set; }
[JsonProperty("popularity")]
public int Popularity { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("cntRooms")]
public int CntRooms { get; set; }
What seems to be the problem? i'm deserializing this using
string resp2 = await client.GetStringAsync("");
var hotelDetails = JsonConvert.DeserializeObject<IDictionary<string, HotelsDescriptionAPI.Root>>(resp2, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
foreach (var hoteldesc in hotelDetails)
{
MessageBox.Show(hoteldesc.Value.Id);
}
and the exact error is
"Error converting value 24545 to type and Error converting value "10:30" to type 'HotelsDescriptionAPI.Root'. Path 'checkOut', line 1, position 19."
Im trying to get the value of "Id", What could be the problem with my code?
Your deserialization code should be:
var hotelDetails = JsonConvert.DeserializeObject<HotelsDescriptionAPI.Root>(resp2,
new JsonSerializerSettings {
NullValueHandling = NullValueHandling.Ignore
});
You're trying to deserialize it into a dictionary of string,Root, when the object itself is simply Root.
It does not seem to apply to your scenario, but note that when you do have JSON that is an array (root level children are array items, not properties), you may have to change the root object to subclass a compatible type.
For example:
public class RootObject : List<ChildObject>
{
}
public class ChildObject
{
public string Property1 { get; set; }
public string Property2 { get; set; }
}
For people that this does not help, and that are not using Entity Framework and or writing the domain classes by hand - make sure all your class properties match what is coming out of your data source in the same exact field order.