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;
Related
I have a local json file that I wish to be able to add a new dictionary to the existing array within the file using data entries from a form.
i.e.
turn this:
[
{
"name": "Product1",
"type": "Drink",
"costS": 2.5,
"costB": 2.4,
"amount": "none",
"info": "keep cold"
}
]
into:
[
{
"name": "Product1",
"type": "Drink",
"costS": "2.5",
"costB": "2.4",
"amount": "none",
"info": "keep cold"
}
{"name": "Product2",
"type": "Food",
"costS": "2.8",
"costB": "4",
"amount": "34",
"info": "keep hot"
}
]
where each value comes from a form element ("name" value from txtName, "type" value from txtType, etc).
I have so far tried adapting answers from this post and this post to no avail.
I am very new to c# so it would be much appreciated if answers could be explained to at least a small degree of depth please. Any replies are appreciated however.
You can do like this by using NewtonSoft.Json. first, deserialize the JSON to List<Example> then add the item to this list. and then finally you can serialize the List<Example> to string.
var list = JsonConvert.DeserializeObject<List<Example>>(json);
Example example = new Example();
example.name = "Product2";
example.info = "keep hot";
example.amount = "34";
example.costB = "4";
example.costS = "2.8";
example.type = "Food";
list.Add(example);
string output = JsonConvert.SerializeObject(list);
public class Example
{
public string name { get; set; }
public string type { get; set; }
public string costS { get; set; }
public string costB { get; set; }
public string amount { get; set; }
public string info { get; set; }
}
I have this json body
[
{
"Id": 1,
"Name": "John",
"Icon": "Icon/someplace",
"SortOrder": 1
},
{
"Id": 2,
"Name": "Jessica",
"Icon": "Icon/someplace",
"SortOrder": 1
},
{
"Id": 3,
"Name": "Kevin",
"Icon": "Icon/someplace",
"SortOrder": 1
},
{
"Id": 4,
"Name": "Lint",
"Icon": "Icon/someplace",
"SortOrder": 1
},
{
...
}
]
I am adding Values to the json via API, I need to verify that the new value is present is the json body
I am trying to Covert the response to json,
public object Get_Json()
{
var response = GEt_Json_Body();
var json_string = JsonConvert.SerializeObject(response);
JArray UpdatedContent = JArray.Parse(json_string);
JObject Facility_Json = JObject.Parse(UpdatedContent[0].ToString());
Assert.NotNull(Facility_Json);
return Facility_Json;
}
This Only gives me back the first json:
{
"Id": 1,
"Name": "John",
"Icon": "Icon/someplace",
"SortOrder": 1
}
UpdatedContent[i] i allows me to get the other jsons in the array, the problem is I don't know where the json I Created using the API will be placed, how to get All of the JArray and verify that my entry is there?
Update:
This is my Call:
public List<FooModel> Get_Json_Body()
{
var request = new RestRequest();
request.Resource = string.Format("/api/get_something");
return Execute<FooMedl>(request, Endpoint);
}
public class FooModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Icon { get; set; }
public int SortOrder { get; set; }
}
public List<T> Execute<T>(RestRequest request, string Endpoint) where T : new()
{
Client.BaseUrl = new Uri(Endpoint);
var response = Client.Execute<List<T>>(request);
Console.WriteLine(response.ResponseUri);
if (response.ErrorException != null)
{
string message = String.Format("Error retrieving response: \n{0} \n{1} \n{2} ",
response.Content, response.ErrorMessage, response.ErrorException);
Console.WriteLine(message);
var exception = new ApplicationException(message);
throw exception;
}
return Response.Data;
}
Update 2:
The Answer By Davig G helped me to solve the problem, Was able to verify my input via
if(data.Any(f => f.Name == "Kevin"))
{
Console.WriteLine("Kevin exists in the data");
}
I am returing a List of dictionaries From Get_Json() method Using DavigG's answer I am able to verify and access the specific keys and values within the list.
It's much easier to deal with concrete classes than pure JSON objects, I would recommend deserialising your JSON directly into a list of objects like this:
public class Foo
{
public int Id { get; set; }
public string Name { get; set; }
public string Icon { get; set; }
public int SortOrder { get; set; }
}
And the code to deserialise is:
var data = JsonConvert.DeserializeObject<List<Foo>>(response);
Now you can treat that object as you wish, for example:
if(data.Any(f => f.Name == "Kevin"))
{
Console.WriteLine("Kevin exists in the data");
}
Or even make modifications:
var kevin = data.SingleOrDefault(f => f.Name == "Kevin");
if(kevin != null)
{
kevin.SortOrder = 3;
}
And then if you need it to be back to the original JSON:
var json = JsonConvert.SerializeObject(data);
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
Im trying to get events from facebook with multiple ids. I works with one ID, but the problem is when im trying to work with multiple ids. I have problem with the json result that i get. The result doesent start with "data" and i cant find help for my issue when its start with the id. Pasting my Json result and C# code here. Thnx.
Json result {
= { {
"167730163274461": {
"data": [
{
"description": "",
"end_time": "2017-05-13T23:00:00+0200",
"name": "Tjuvjakt (SE) LIVE på Babel",
"place": {
"name": "Babel Malmö",
"location": {
"city": "Malmö",
"country": "Sweden",
"latitude": 55.596131504101,
"longitude": 13.010933324378,
"street": "Spångatan 38",
"zip": "211 53"
},
"id": "167730163274461"
},
"start_time": "2017-05-13T19:30:00+0200",
"id": "1188647557883179"
},
"157257114335823": {
"data": [
{
"description": "",
"end_time": "2017-05-21T03:00:00+0200",
"name": "Morrissey / The Smiths - Unhappy Birthday Party",
"place": {
"name": "Moriska Paviljongen",
"location": {
"city": "Malmö",
"country": "Sweden",
"latitude": 55.593787653743,
"longitude": 13.013644627863,
"street": "Norra Parkgatan 2",
"zip": "21422"
},
"id": "157257114335823"
},
"start_time": "2017-05-20T23:00:00+0200",
"id": "1208509892563996"
},
}
List<FbEvents> listOfEvents;
public ActionResult Index()
{
WebClient myWebClient = new WebClient();
string downloadUrl = "https://graph.facebook.com/events?ids=167730163274461,157257114335823&access_token=**=40";
Uri downloadUri = new Uri(downloadUrl, UriKind.Absolute);
string downloadedJsonResult = null;
try
{
downloadedJsonResult = myWebClient.DownloadString(downloadUri);
}
catch (Exception ex)
{
ViewBag.ErrorMessage = ex.ToString();
return View("Error");
}
JObject jsoncreatestring = JObject.Parse(downloadedJsonResult);
JArray requiredDataArray = (JArray)jsoncreatestring["167730163274461"]["data"];
string stringToBe = requiredDataArray.ToString();
listOfEvents = JsonConvert.DeserializeObject<List<FbEvents>>(stringToBe);
return View(listOfEvents);
}
}
}
public class FbEvents
{
[JsonProperty("owner")]
public string owner { get; set; }
[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("start_time")]
public string date { get; set; }
[JsonProperty("description")]
public string description { get; set; }
[JsonProperty("cover")]
public Dictionary<string, string> cover { get; set; }
[JsonProperty("id")]
public string id { get; set; }
}
I don't think it's the best way to do it but it should work like this:
// [...]
JObject jsoncreatestring = JObject.Parse(downloadedJsonResult);
List<FbEvents> listOfEvents = new List<FbEvents>();
foreach (var item in jsoncreatestring)
{
JArray requiredDataArray = (JArray)item.Value["data"];
FbEvents fbEvent = JsonConvert.DeserializeObject<List<FbEvents>>(requiredDataArray.ToString())[0];
listOfEvents.Add(fbEvent);
}
return View(listOfEvents);
// [...]
How to parse data in a List from JSON data like following link using C# ?
{
"voters": [{
"id": "5644309456813",
"name": "Rimi Khanom",
"address": "House no: 12. Road no: 14. Dhanmondi, Dhaka",
"date_of_birth": "1979-01-15"
}, {
"id": "9509623450915",
"name": "Asif Latif",
"address": "House no: 98. Road no: 14. Katalgonj, Chittagong",
"date_of_birth": "1988-07-11"
}, {
"id": "1098789543218",
"name": "Rakib Hasan",
"address": "Vill. Shantinagar. Thana: Katalgonj, Faridpur",
"date_of_birth": "1982-04-12"
}, {
"id": "7865409458659",
"name": "Rumon Sarker",
"address": "Kishorginj",
"date_of_birth": "1970-12-02"
}, {
"id": "8909854343334",
"name": "Gaji Salah Uddin",
"address": "Chittagong",
"date_of_birth": "1965-06-16"
}]
}
try this :
public class Voter
{
public string id { get; set; }
public string name { get; set; }
public string address { get; set; }
public string date_of_birth { get; set; }
}
public class RootObject
{
public List<Voter> voters { get; set; }
}
var VoterModel = JsonConvert.DeserializeObject<List<Voter>>(json);
You are getting an array of objects from the JSON. So all you need is to do a foreach on the voters. JavaScript objects are mapped to Dictionary<string, object> in C#. Pseudo code
using System.Web.Script.Serialization;
using System.Net;
using (var client = new WebClient())
{
var url = "http://nerdcastlebd.com/web_service/voterdb/index.php/voters/all/format/json";
var jsonString = client.DownloadString(url);
var json = new JavaScriptSerializer().Deserialize<dynamic>(jsonString);
foreach (Dictionary<string, object> voter in json["voters"])
{
var id = voter["id"].ToString();
// pull name, address and date_of_birth here
}
}