In the Norway they have a register of organisations (brreg.no), which you can access through a webservice. If an organisation owns one or more other organisations, you can also access a list of those.
Now my problem is this: I would like to create a class for the parrent organisation and populate it with DataContractJsonSerializer. That par is easy. What I would also like to do, is to have a List<ChildrenOrganisation> in the parent class. This would also be easy, if the parrent and children organisation were in the same JSON file. But they are not. Is there a way to work around this, perhaps merging two different Streams?
Here is my how I get the HTTP Web Response:
public async Task GetHttpWebRespsoneAsJson(bool isSubOrganisation)
{
string href;
string requestString;
// Set the request string, depending on whether or not it is a sub-organisation
if (isSubOrganisation)
{
href = "http://data.brreg.no/enhetsregisteret/underenhet.json?page=0&size=100&$filter=overordnetEnhet+eq+{0}";
requestString = String.Format(href, organisationNumber);
}
else
{
href = "http://data.brreg.no/enhetsregisteret/enhet/{0}.json";
requestString = String.Format(href, organisationNumber);
}
// Create the HTTP request, using the input parameters
WebRequest httpRequest = WebRequest.Create(requestString);
// Get the respone of the HTTP request
httpResponse = await httpRequest.GetResponseAsync();
// Get the statuscode (hopefully "OK")
httpStatus = ((HttpWebResponse)httpResponse).StatusCode;
}
Here is my implementation of DataContractJsonSerializer:
public CompanyModel GetCompany()
{
CompanyModel company = new CompanyModel();
using (Stream httpDataStream = httpResponse.GetResponseStream())
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(CompanyModel));
company = (CompanyModel)ser.ReadObject(httpDataStream);
httpDataStream.Close();
}
return company;
}
The parent organisation simplifed (see an actual example here):
{
"organisationId": 123,
"name": "Parent Organisation",
"address": {
"streetname": "Electric Avenue",
"number": 42,
"city": "Los Angeles"
}
}
The list of children organisations simplified (see an actual example here):
"organisations": [
{
"organisationId": 456,
"parentOrganisation": 123,
"name": "Children Organisation 1",
"address": {
"streetname": "Sunset Boulevard",
"number": 69,
"city": "San Fransisco"
}
},
{
"organisationId": 789,
"parentOrganisation": 123,
"name": "Children Organisation 2",
"address": {
"streetname": "Ocean Drive",
"number": 13,
"city": "Miami"
}
}
]
Related
Example JSON, for example say I want the quote and author values. I wasn't able to get them unless I built a model around the JSON, which I'm not wanted to do as it would be more time consuming.
{
"success": {
"total": 1
},
"contents": {
"quotes": [
{
"quote": "Plant your own garden and decorate your own soul, instead of waiting for someone to bring you flowers.",
"length": "102",
"author": "Veronica A. Shoffstall",
"tags": [
"flowers",
"inspire",
"self-help",
"soul"
],
"category": "inspire",
"language": "en",
"date": "2022-12-22",
"permalink": "https://theysaidso.com/quote/veronica-a-shoffstall-plant-your-own-garden-and-decorate-your-own-soul-instead-o",
"id": "LQbKQGxVA2rcH4lIwn6OIweF",
"background": "https://theysaidso.com/img/qod/qod-inspire.jpg",
"title": "Inspiring Quote of the day"
}
]
},
"baseurl": "https://theysaidso.com",
"copyright": {
"year": 2024,
"url": "https://theysaidso.com"
}
}
My test example code with URL below. I tried it with Dynamic Object but can never get to the string.
try
{
private static readonly HttpClient _httpClient = new HttpClient();
// Make the API request
var response = _httpClient.GetAsync("https://quotes.rest/qod?language=en").Result;
response.EnsureSuccessStatusCode();
// Do something with the response
var value11 = response.Content.ReadAsStringAsync().Result;
var gett = JsonConvert.DeserializeObject<dynamic>(value11);
var quote= gett.contents.quotes.quote;
return quote;
}
catch (Exception ex)
{
quote = ex.Message;
return quote;
}
Looking at the JSON structure the quotes property is an array and as such you should use
var quote = gett.contents.quotes[0].quote;
Assuming that deserialization was not the cause of the failure.
There is no json convert error. quotes is array you can access gett .contents.quotes[0].quote.
Tips; you don't need to json convert and ReadAsString you can easily use like response.Content.ReadFromJsonAsync().Result?.contents.quotes[0].quote
I have a Json String that I get from a web service; it has a list of collections, each collection represents an object, for example:
[ // Root List
[ // First Collection : Team Object
{
"id": 1,
"team_name": "Equipe Saidi",
"is_active": true,
"last_localisation_date": "2015-05-06T13:33:15+02:00"
},
{
"id": 3,
"team_name": "Equipe Kamal",
"is_active": true,
"last_localisation_date": "2015-05-06T09:22:15+02:00"
}
],
[// Second Collection : user Object
{
"id": 1,
"login": "khalil",
"mobile_password": "####",
"first_name": "Abdelali",
"last_name": "KHALIL",
"email": "KHALIL#gmail.com",
"role": "DR",
"is_active": true,
"charge": false
},
{
"id": 2,
"login": "ilhami",
"mobile_password": "####",
"first_name": "Abdellah",
"last_name": "ILHAMI",
"email": "ILHAMI#gmail.com",
"role": "DR",
"is_active": true,
"charge": false
}
]
]
My actual code (not working of course ):
public async Task TeamsAndMobileUsers()
{
string data = "";
IList<User> MobileUsersList = new List<User>();
IList<Team> TeamsList = new List<Team>();
try
{
data = await GetResponse(PATH + TEAMS_USERS_URL);
TeamsList = JsonConvert.DeserializeObject<List<Team>>(data);
MobileUsersList = JsonConvert.DeserializeObject<List<User>>(data);
// Inserting
await SetAchievedActions(TeamsList);
}
catch (Exception e) {
_errors.Add(e.Message);
}
}
I use Json.net and C#. I can't find a solution, I've read that I should use JsonReader and set its SupportMultipleContent property to true but I don't know how to implement that solution.
As #YeldarKurmangaliyev already said, your json has two different objects, I think you can do something like this:
var j = JArray.Parse(data);
TeamsList = JsonConvert.DeserializeObject<List<Team>>(j[1].ToString());
MobileUsersList = JsonConvert.DeserializeObject<List<User>>(j[2].ToString());
have you tried http://json2csharp.com/ to generate contract classes for that json? also, first and last parenthesis gives a not valid JSON
You need to create 4 classes
1st class TeamObject : Variable(id,team_name,is_active,last_localisation_date)
2nd class UserObject : Variable (id, login,mobile_password,first_name, last_name , email, role,is_active,charge)
3rd class RootList: Variable ( arraylist<TeamObject> obj, arraylist<UserObject > obj2)
4th class RootClass : Variable(arraylist<RootList> obj)
Gson gson=new Gson();
RootClass dtomodel = gson.fromJson(data , RootClass .class);
This parsing done using Gson Library
I am trying to post a new item creation to a test store via C#, but I'm not sure how the syntax should read. Square Connect API requires at least one variation for new item creation, but I'm not sure how to add that to the JSON body. Here is what I have, but I'm not sure how to complete it.
var client = new RestSharp.RestClient();
var post = new RestRequest("https://connect.squareup.com/v1/me/items", Method.POST);
post.RequestFormat = DataFormat.Json;
post.AddHeader("Authorization", String.Format("Bearer {0}", testtoken));
post.AddBody(new { name = testname, variations = ???? });
This code works, but returns a response of an item must include at least one variation. I realize that, but do not know how to write it, or if it is even possible.
I am not opposed to going a different route.
Edited to add a sample request body from the Square documentation:
{
"name": "Milkshake",
"description": "It's better than yours",
"visibility": "PRIVATE",
"category_id": "36ac7016-3a4e-4934-81f1-9057ac613f2y",
"variations": [
{
"name": "Small",
"pricing_type": "FIXED_PRICING",
"price_money": {
"currency_code": "USD",
"amount": 400
},
"sku": "123"
}
]
}
Something like this should serialize to JSON in the correct format:
post.AddBody(new {
name = testname,
variations = new object[] {
new {
name = "Small",
pricing_type = "FIXED_PRICING",
price_money = new {
currency_code = "USD",
amount = 400
}
}
},
sku = "123"
});
The URL Is:
http://reportguru.webdenza.com/vdetect-pro-2/api.php?q={\"svc\":\"auth\",\"params\":{\"username\":\"username\",\"password\":\"passowrd\"}}
The username and password should come from textboxes.Asp.net(c#) code is needed.
After passing the credentials the following json will come.
{ "items":
{ "642163":
{ "id": 642163,
"nm": "AK-21699-11-Lancer-Mohammed Al Noman" },
{ "642169":
{ "id": 642169,
"nm": "AK-21699-11-Lancer-Mohammed Al Noman" } ,
{ "642063":
{ "id": 642063,
"nm": "AK-21699-11-Lancer-Mohammed Al Noman" }
},
"sid": "fdf47003cc1eca9133822ba0025c6aea",
"count": 12,
"p_type": "hst"
}
fdf47003cc1eca9133822ba0025c6aea
All the items should come.I have 642163 like id 100.How get all these values in asp.net(c#).
Use System.Web.Script.Serialization.JavaScriptSerializer and it's Deserialize method to get a strong typed access to the JSON response.
If you don't mind adding new references, you could also have a look at Json.NET
i have json string as :
{
"data": [
{
"id": "100000045402409_310121622373595",
"from": {
"name": "Ritesh Ranjan",
"id": "100000045402409"
},
"message": "greatttttttttttttt ab jaooooooooo",
"picture": "http://external.ak.fbcdn.net/safe_image.php?d=AQAGY5rsr5AeM5PI&w=90&h=90&url=http\u00253A\u00252F\u00252Fwww.ndtv.com\u00252Fnews\u00252Fimages\u00252Ftopstory_thumbnail\u00252FChidambaram_2G_120.jpg",
"link": "http://www.ndtv.com/article/india/2g-scam-chidambaram-verdict-expected-shortly-huge-implications-for-govt-173168",
"name": "2G scam: Chidambaram verdict expected shortly, huge implications for govt",
"caption": "www.ndtv.com",
"description": "A Delhi court handling the 2G spectrum allocation scam trial is likely to decide today whether Union Home Minister P Chidambaram should be made a co-accused in the case for allegedly allowing former Telecom Minister A Raja to gift mobile network licenses and scarce second-generation or 2G spectrum a...",
"icon": "http://static.ak.fbcdn.net/rsrc.php/v1/yD/r/aS8ecmYRys0.gif",
"type": "link",
"application": {
"name": "Links",
"id": "2309869772"
},
"created_time": "2012-02-04T11:02:22+0000",
"updated_time": "2012-02-04T11:02:22+0000"
},
{
"id": "100003303253347_132959650157476",
"from": {
"name": "Suman Dey",
"id": "100003303253347"
},
"message": "Check out this article I was reading on biNu. 2G verdict: Chidambaram off the hook, government exhales",
"type": "status",
"application": {
"name": "biNu",
"canvas_name": "binuapp",
"namespace": "binuapp",
"id": "378628085054"
},
"created_time": "2012-02-04T10:54:19+0000",
"updated_time": "2012-02-04T10:54:19+0000"
},
.....
//Continued...
Now i want to parse it using c#
i have used :
WebClient client = new WebClient();
string Json = client.DownloadString("https://graph.facebook.com/search?q=2g+verdict+Chidambaram&type=post");
System.IO.StreamWriter SW = new System.IO.StreamWriter(JsonDestFile);
SW.WriteLine(Json);
System.IO.StreamWriter SW1 = new System.IO.StreamWriter(ValuesDestFile);
JObject o = JObject.Parse(Json);
var postTitles = from p in o["data"].Children()["from"]
select p["name"].Values<string>();
foreach (var item in postTitles)
{
SW1.WriteLine(item);
}
SW1.WriteLine(name);
But i am not able to get any name values at all.
Its giving me error : Cannot access child value on Newtonsoft.Json.Linq.JValue.
Please suggest me how can i parse the above json for values of id, name, id (from one) , message
I got it working...
var postTitles = from p in JO["data"].Children()
select new
{
Names = (string)p["from"]["name"],
Msg = (string)p["message"],
};
Using this LINQ i can access the required data.
I haven't used the LINQ to JSON API, but if you don't insist on using it you can simply create a class that models the data in your JSON payload and then use the following method:
Newtonsoft.Json.JsonConvert.DeserializeObject<YourDataModelClass>()
you need to deseriralise the json string as shown below
public static T Deserialise<T>(string json)
{
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
var serialiser = new DataContractJsonSerializer(typeof(T));
return (T)serialiser.ReadObject(ms);
}
}
Return type is you class
public class MyData
{
public string id { get; set;}
public string name{ get; set;}
public string message{ get; set;}
}
you can check full details : Parse JSON in C#
This also will work
JObject hh = JObject.Parse(jsonstring);
string name = (string)hh["Name"];