I need to do a basic update to a JSON package using FormUrlEncodedContent
At the moment, I can only assign values at parent level.
For example, here's the JSON package that will be sent through the API.
[
{
"id": 29519,
"first_name": "xxxx",
"last_name": "xxx",
"billing": {
"address_1": "xxxx",
"address_2": "xxxx"
}
}
]
At the moment, I can only update the first_name and last_name values using the following code:
var UpdateCustomerAPI = "https://example.com/api/";
var UpdateCustomer_JSON = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string,string>("first_name", CustomerFirstName.Text),
new KeyValuePair<string,string>("last_name", CustomerLastName.Text)
});
var httpClient = new HttpClient();
var response = httpClient.PutAsync(UpdateCustomerAPI, UpdateCustomer_JSON);
How do I update the values in billing:address_1 and billing:address_2 using the FormUrlEncodedContent?
You don't: https://learn.microsoft.com/en-us/dotnet/api/system.net.http.formurlencodedcontent?view=netcore-3.1
A container for name/value tuples encoded using application/x-www-form-urlencoded MIME type.
From https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST
application/x-www-form-urlencoded: the keys and values are encoded in key-value tuples separated by '&', with a '=' between the key and the value.
You are not putting a json file to your server. If you want to use it, then you should do something like:
var UpdateCustomer_JSON = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string,string>("billing_address_1", CustomerBillingAddress.Text),
});
If you want to post a json file, then you should use application/json mine type and use something like this:
var data = JsonConvert.SerializeObject(customerData);
Related
I have set a WebHook and i am receiving a mixed Content, which after Url Decoding, this is what i get:
chat_id=222231&from={"id":201232,"name":"John","user":"User_Admin"}&type=text&data=yes
i Serialized it like so:
var json = new JavaScriptSerializer().Serialize(
encode.Keys.Cast<string>()
.ToDictionary(k => k, k => encode[k]));
then when using:
var jobject = JObject.Parse(json.ToString());
i get:
{
"chat_id": "222231",
"from": "\"{\"id\":201232,\"name\":\"John\",\"user\":\"User_Admin\"}\"",
"type": "text",
"data": "yes"
}
Well, i could access "from" by parsing it, but shouldn't there be a better way to do this !!? if creating a class will do it then how does it look !!? because no matter how i did it, it just returned null for the "form"
I have a problem on data parsing, I am using C# in Visual Studios and I need a parsing algorithm for my json file. This is the structure:
{
"objects": {
"minecraft/sounds/mob/stray/death2.ogg": {
"hash": "d48940aeab2d4068bd157e6810406c882503a813",
"size": 18817
},
"minecraft/sounds/mob/husk/step4.ogg": {
"hash": "70a1c99c314a134027988106a3b61b15389d5f2f",
"size": 9398
},
"minecraft/sounds/entity/rabbit/attack2.ogg": {
"hash": "4b90ff3a9b1486642bc0f15da0045d83a91df82e",
"size
I want to pull "minecraft/sounds/mob/stray/death2.ogg" and "hash" the data.
My C# code:
HttpWebRequest reqobje = WebRequest.Create(assetsurl) as HttpWebRequest;
using (HttpWebResponse response = reqobje.GetResponse() as HttpWebResponse)
{
StreamReader objejsonsr = new StreamReader(objectjson);
jsonVerisi = objejsonsr.ReadToEnd();
}
parser = JObject.Parse(jsonVerisi);
JToken job = parser["objects"];
Since you're using json.net, you can deserialize the string into any object you need. The sample below is an anonymous type with dictionary so you can use the dynamic keys that are coming back:
var result = JsonConvert.DeserializeAnonymousType(jsonVerisi, new { objects =
new Dictionary<string, Dictionary<string, string>>() });
var objects = result.objects; // key/value;
This is one way you can use it (maybe even to map to your own model instead of anonymous types to make it easier to work with):
var objects = result.objects
.Select(m => new
{
Path = m.Key,
Hash = m.Value["hash"],
Size = int.TryParse(m.Value["size"], out var value) ? value : 0,
}).ToList();
var path = objects[0].Path; // Get the path of the first object
So I what I am trying to do is capture/extract specific data from Steams API for dota2 heroes. I am using C# to do this with this method.
https://api.steampowered.com/IEconDOTA2_570/GetHeroes/v0001/?key=2D13D618DA712015812E970165632F02&language=en_us
{
"result": {
"heroes": [
{
"name": "npc_dota_hero_antimage",
"id": 1,
"localized_name": "Anti-Mage"
},
]
}
This is the code I have been trying with:
WebClient c = new WebClient();
var data = c.DownloadString("https://api.steampowered.com/IEconDOTA2_570/GetHeroes/v0001/?key=2D13D618DA712015812E970165632F02&language=en_us");
JObject o = JObject.Parse(data);
string heroname = (string)o["name"];
But it only returns an error saying the value of "heroname" is null.
Any ideas?
o is going to be an object that contains one key: result. o["result"] will in turn contain a key called heroes. o["result"]["heroes"] is an array of objects. So o["result"]["heroes"][0] will be the first item, and o["result"]["heroes"][0]["name"] is the name from the first item.
So I am given a json tree like the one below and I really just need to get the persons first and last names from here but I am having problems parsing the data.
{
"results":[
{
"id":{
"key":"Phone.81dd6fef-a2e2-4b08-cfe3-bc7128b43786.Durable",
"url":"https://proapi.whitepages.com/2.1/entity/Phone.81dd6fef-a2e2-4b08-cfe3-bc7128b43786.Durable.json?api_key=",
"type":"Phone",
"uuid":"81dd6fef-a2e2-4b08-cfe3-bc7128b43786",
"durability":"Durable"
},
"line_type":"Landline",
"belongs_to":[
{
"id":{
"key":"Person.1ffee2ef-cc88-4a1e-87b0-05349571b801.Durable",
"url":"https://proapi.whitepages.com/2.1/entity/Person.1ffee2ef-cc88-4a1e-87b0-05349571b801.Durable.json?api_key=",
"type":"Person",
"uuid":"1ffee2ef-cc88-4a1e-87b0-05349571b801",
"durability":"Durable"
},
"type":"Full",
"names":[
{
"salutation":null,
"first_name":"fred",
"middle_name":null,
"last_name":"jones",
"suffix":null,
"valid_for":null
}
],
"age_range":null,
"gender":null,
"locations":[
{
"id":{
"key":"Location.bd4721f0-ba97-4ade-aac1-ed1f16be57ed.Durable",
"url":"https://proapi.whitepages.com/2.1/entity/Location.bd4721f0-ba97-4ade-aac1-ed1f16be57ed.Durable.json?api_key=",
"type":"Location",
"uuid":"bd4721f0-ba97-4ade-aac1-ed1f16be57ed",
"durability":"Durable"
},
"type":"Address",
"valid_for":{
"start":{
"year":2011,
"month":7,
"day":5
},
"stop":null
},
"legal_entities_at":null,
"city":"",
"postal_code":"",
"zip4":null,
"state_code":"",
"country_code":"",
"address":"",
"house":"10",
"street_name":"",
"street_type":"Ave",
"pre_dir":null,
"post_dir":null,
"apt_number":null,
"apt_type":null,
"box_number":null,
"is_receiving_mail":false,
"not_receiving_mail_reason":null,
"usage":null,
"delivery_point":null,
"box_type":null,
"address_type":null,
"lat_long":{
"latitude":,
"longitude",
"accuracy":"Street"
},
"is_deliverable":true,
"standard_address_line1":"",
"standard_address_line2":"",
"standard_address_location":"",
"is_historical":false,
"contact_type":"Home",
"contact_creation_date":1361177323
}
],
The code I have been using so far is:
string url = String.Format("https://proapi.whitepages.com/2.1/phone.json?api_key={0}&phone_number={1}", WhitePagesConstants.ApiKey, number);
using (WebClient webClient = new System.Net.WebClient())
{
WebClient n = new WebClient();
n.Encoding = System.Text.Encoding.UTF8;
var json = n.DownloadString(url);
Dictionary<string, Object> formattedjson = JsonConvert.DeserializeObject<Dictionary<string, Object>>(json);
}
I have been on this for too long and must finish it shortly so I ask please help me traverse this tree. I have never worked with json before and am quite lost on how to do this. The exact info I need is under "belongs_to" -> "names" -> first and last. I've changed some names to protect the innocent.
If all you need is to extract several properties, you can just navigate the path:
dynamic o = JsonConvert.DeserializeObject(json);
Console.WriteLine(o.results[0].belongs_to[0].names[0].first_name);
Console.WriteLine(o.results[0].belongs_to[0].names[0].last_name);
Or, if you prefer string dictionaries over dynamic objects:
JObject j = JsonConvert.DeserializeObject<JObject>(json);
Console.WriteLine(j["results"][0]["belongs_to"][0]["names"][0]["first_name"]);
Console.WriteLine(j["results"][0]["belongs_to"][0]["names"][0]["last_name"]);
P.S. Your JSON is broken. It would have been easier for me to test code if you provided a correct example.
I have an ASP.NET MVC app. I am trying to hit an external web service from the controller in my app. Currently, I am hitting the web service like this:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(baseAddress);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.GetAsync(GetServiceUrl());
dynamic data = System.Web.Helpers.Json.Decode(...)
}
The result from the web service can have three different schemas in JSON. They look like this;
schema 1
{
"request":"some info",
"value": [
{"id":1, name:"bill" },
{"id":2, name:"john" }
]
}
schema 2
{
"request":"some info",
"value": [
{ "orderId":"A12345", orderDate:"10-12-2014" },
{ "orderId":"B31234", orderDate:"11-01-2014" },
{ "orderId":"C36512", orderDate:"12-03-2014" },
]
}
schema 3
{
"request":"some info",
"value": [
{ "productId":"11-22-33", "name":"ball", "description":"a round thing" },
{ "productId":"3A-12-52", "name":"tire", "description":"keeps you moving" },
{ "productId":"7D-xy-23", "name":"plate", "description":"something to eat off of." },
]
}
I would like to avoid writing three separate classes if at all possible. I really only want to do two things: 1) count the number of objects in the value array. 2) Loop through the objects in the value array and print out some of the values via Razor.
Can I do these two things without creating 3 new classes? If so, how?
THank you!
Assuming you're using json.net, you can use JObject and JArray.
var json = #"{'value': [ { 'id' : 1}, { 'id' : 2 } ]}";
var jObject = JObject.Parse(json);
var values = (JArray) jObject["value"];
Console.WriteLine("Number of items: {0}", values.Count);
foreach (var value in values)
{
// do something with value.
}
If you're not using json.net, you could go with Robert Harvey's suggestion and use JavaScriptSerializer.
var jsonDict = serializer.Deserialize<IDictionary<string, object>>(json);
var array = (IEnumerable<object>) jsonDict["value"];