Recently I got an appointment where I need to download some data from Cloud using it's REST API and store the values from that "string" in an object or in some variables. The download is done, all I need to do now is to parse somehow the data.
Until now i made this kind of code:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("some link");
request.ContentType = "application/json; charset=utf-8";
request.Method = "GET";
request.Headers.Add("Carriots.apiKey", "key");
using (WebResponse response = request.GetResponse())
{
using(Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream);
JObject json = JObject.Parse(reader.ReadToEnd());
Console.WriteLine(json.ToString());
}
}
And here is the output:
{
"total_documents": 3,
"result": [
{
"_id": "...",
"protocol": "v1",
"checksum": "",
"_t": "str",
"at": 1444134377,
"device": "-just a device-",
"data": {
"field1": "123",
"field2": "1536"
},
"id_developer": "....",
"created_at": 1444134377,
"owner": "-someUser-"
}
]
}
I know that there are a lot of solutions on the internet, but none of them does what I need. Okay, I found something, but that iterates on every line and checks the values that way, but in my case I can have thousands of outputs like this.
Are there any ways to do all that (I mean the parsing) using some kind of built-in functions or the only solution is to iterate or write some regular expression?
assuming the json will always follow this format, define your model
public class jsonData{
public int total_documents {get;set;}
public resultData result {get;set;}
}
public class resultData{
public int _id {get;set;}
public string protocol {get;set;}
....
}
then use deserialize
Json.Deserialize<jsonData>(yourstring)
Related
Trying to deserialize objects from HTTP response.
Response stream returns information in json and I already checked if it is valid in online deserializer.
I got the object class from the API framework so I think all of the properties should be configured for the response.
Code:
var request = new HttpRequestMessage(HttpMethod.Get,
"api_url");
var client = _clientFactory.CreateClient();
var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
using var responseStream = await response.Content.ReadAsStreamAsync();
var reponseString = await response.Content.ReadAsStringAsync();
var data = await JsonSerializer.DeserializeAsync<IEnumerable<Tournament>>(responseStream);
}
else
{
GetBranchesError = true;
}
I see that information in responseString is correct but data objects are always null.
Weird part is that it partially works because it shows how many objects are in the responseStream but all of the object properties are nulls.
Also tried to set the stream position to 0 - didn't help.
Any idea what I am doing wrong to deserialize these objects?
Desirializer used - System.Text.Json;
Project asp .net core 3.1
The problem is that the properties you are looking for in the JSON array are actually wrapped inside an object called "tournament". It's easier to notice when you format the JSON string nicely like this for example:
[
{
"tournament": {
"id": 1,
"name": "name1",
...
}
},
{
"tournament": {
"id": 2,
"name": "name2",
...
}
}
]
To deserialize this I would suggest you make a wrapper class to handle that:
public class TournamentItem
{
[JsonPropertyName("tournament")]
public Tournament Tournament { get; set; }
}
And then deserialize to that class:
var data = await JsonSerializer.DeserializeAsync<IEnumerable<TournamentItem>>(responseStream);
Now data.Tournament will contain all the properties.
There might still be a few issues in your properties like Spam for example. The JSON string has a null as value, but the property is not nullable - I didn't check all your properties. DeserializeAsync will throw an error and tell you.
I want help how to take text from response of http here the source of request
var request = (HttpWebRequest)WebRequest.Create("https://xxxx.com/");
var postData = "{"+'"'+"get"+ '"' +":100}";
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "PUT";
request.ContentType = "application/json";
request.Headers["X"] = "83ed3926";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
now i want source code to can search in : responseString
Example:
{"auctionInfo":[{"IDEF":224454585435,"itemData":2 ","buyNowPrice":100,"
,{"IDEF":224454839937,"itemData":","buyNowPrice":200,"{"IDEF":315779793672,"timestamp":1539055787,"formation":"f352","Price":100,"assetrd":1,"rating":","buyNowPrice":300,"
I want way to take the first IDEF and buynowprice and to add them to two strings.
Example if will run the code will be:
IDEF = 224454839937
buyNowPrice = 100
To take only the first the other just skips.
As you can see your data have some structure inside that json string and that is object like this:
public class Item
{
public int IDEF { get; set; }
public int itemData { get; set; }
public float buyNowPrice { get; set; }
}
So this is c class that is representing structure inside that json string.
Only thing left is to Deserialize that json string and you will do it like this:
List<Item> items = JsonConvert.DeserializeObject<List<Item>>(yourJsonStringHere);
And there you have it, list full of objects of class Item.
The first problem here is that your JSON (the text) is broken...
It should look like this:
{
"auctionInfo": [
{
"IDEF": 224454585435,
"itemData": 2,
"buyNowPrice": 100
},
{
"IDEF": 224454839937,
"itemData": 0,
"buyNowPrice": 200
},
{
"IDEF": 315779793672,
"timestamp": 1539055787,
"formation": "f352",
"Price": 100,
"assetrd": 1,
"rating": 0,
"buyNowPrice": 300
}
]
}
You can explore that JSON above at this site.
Now that the JSON is in the correct format, you can parse it using a Nuget package called NewtonSoft JSON:
using System;
public class Program
{
public static void Main()
{
var json = "{\"auctionInfo\":[{\"IDEF\":224454585435,\"itemData\":2,\"buyNowPrice\":100},{\"IDEF\":224454839937,\"itemData\":0,\"buyNowPrice\":200},{\"IDEF\":315779793672,\"timestamp\":1539055787,\"formation\":\"f352\",\"Price\":100,\"assetrd\":1,\"rating\":0,\"buyNowPrice\":300}]}";
dynamic theObject = Newtonsoft.Json.Linq.JObject.Parse(json);
dynamic auctionInfo = (Newtonsoft.Json.Linq.JArray)theObject.auctionInfo;
var theFirstItem = auctionInfo[0];
var idef = theFirstItem.IDEF;
var price = theFirstItem.buyNowPrice;
Console.WriteLine(string.Format("IDEF: {0}, Price: {1}",idef,price));
}
}
The first part of the JSON is an object (this is why we parse to a JObject), but it contains an array called "auctionInfo". We must therefore cast theObject.auctionInfo to a JArray. Finally, you want the first item from array and so we take the item at the 0 index...
The item at index 0 has what you want (the IDEF and the price), and so we then print them to the console.
You can see this code and run it here.
I have reviewed a lot of posts about this question and I am still having trouble. I am using Newtonsoft.Json and the following code:
string url = #"https://https://someSite.com/indexes('myIndex')search=SEARCH_PHONES:";
string phoneNumber = "5550005555";
url += phoneNumber;
HttpWebRequest request = HttpWebRequest.CreateHttp(url);
request.Method = "GET";
request.Headers.Add("api-key", "####");
WebResponse response = request.GetResponse();
Stream imageStream = response.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader readStream = new StreamReader(imageStream, encode);
string s = readStream.ReadToEnd();
JObject joResponse = JObject.Parse(s);
JArray array = (JArray)joResponse["value"];
string customer = array[0].ToString();
The problem is that array is returning as one long string. How do I access the individual key/value pairs? Below is the response I recieve:
{
"#odata.context": "https://someSite.com/indexes('myIndex')/$metadata#docs",
"value": [
{
"#search.score": 10.933167,
"CUSTOMER_DIM_ID": "77049309",
"SOURCE_CUSTOMER_ID": null,
"PORTSTORE_ID": "0326_1448401",
"FIRST_NM": "First Name",
"LAST_NM": "Last Name",
"ADDR_LINE_1": "133 Main St",
"ADDR_LINE_2": null,
"CITY": "MyCity",
"STATE_CD": "IL",
"POSTAL_CD": "99999",
"COUNTRY": "United States",
"EMAIL_ADDR": "myEmail#gmail.com",
"BIRTH_DT": null,
"PHONE": "5550005555",
"GENDER_CD": "F",
"SEARCH_EMAILS": [
"myEmail#gmail.com"
],
"SEARCH_PHONES": [
"5550005555"
],
"JUS_EMAIL_OPTIN": true,
"JCA_EMAIL_OPTIN": true,
"LCA_EMAIL_OPTIN": true,
"JUS_DM_OPTIN": true,
"JCA_DM_OPTIN": true,
"LCA_DM_OPTIN": true,
"MOBILE_OPTIN": false,
"LIFETIME_REVENUE": "138.1800",
"LIFETIME_UNITS": 7,
"NTH_ORDER": 2,
"FIRST_PURCHASE_DT": "2016-02-11T00:00:00Z",
"LAST_PURCHASE_DT": "2016-02-19T00:00:00Z",
"AVG_LAG": 8,
"IsDeleted": false,
"UPDATE_DT": "2016-02-19T00:00:00Z"
}
]
}
I don't have access to change the response. I tried to use json2sharp to create the objects and then simply deserialize but it said that the "#search.score" was invalid as well as "#odata.context". After I commented out those lines in my C# code it does not deserialize correctly (everything is null) I need to be able to retrieve the customer information and assign it to my custom class.
It looks like you're doing a little extra work here. Instead of
Stream imageStream = response.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader readStream = new StreamReader(imageStream, encode);
string s = readStream.ReadToEnd();
Do string s = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
Then, you can do a JsonConvert.DeserializeObject<MyType>(s) and that should get you your object.
Also in your object, make sure to use the appropriate serialization attributes wherever your names don't match up, if you wanted a particular naming style for example.
Don't manually parse through JSON unless you have a really good reason to do so.
Make a web request using your rest client of choice (postman/dhcp/etc.) and copy the response. Then create a new .cs file and go to Edit -> Past Special -> Paste Json as class.
From here you should get a mostly working POCO that can be used for deserializing the JSON using Newtonsoft.Json.JsonConvert.Deserialize<Class>(responseJson).
Note that newtonsoft defaults to camel case for json properties. Since your properties are not camel case, you need to explicitly define the property name.
[JsonProperty("ID")]
public int ID { get; set; }
Im trying to get a cryptocurrency last price value from a HTTP API:
The following piece of code:
// Create the web request
HttpWebRequest request =
WebRequest.Create("APISITE") as
HttpWebRequest;
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
currentXRPPrice.Text = (reader.ReadToEnd());
}
Gives me the following response which is correct:
{"high": "1.15600", "last": "1.08269", "timestamp": "1518697359", "bid": "1.08034", "vwap": "1.09634", "volume": "40858340.75727354", "low": "1.03051", "ask": "1.08269", "open": "1.13489"}
What I want is just the value of "last" which is "1.08269".
I have tried using this post: [link] (Remove characters after specific character in string, then remove substring?)
which has worked wonders for me on previous projects. But I cant seem to figure out where I am going wrong.
Iv tried below to get the value of "last" but its completely wrong, I have tried many of the different combinations to get it right but its not working to show me just the value for "Last".
response = currentXRPPrice.Text;
response = response.Remove(response.LastIndexOf(":") + 1);
profitLossText.Text = response; //Still wrong tried 4 combinations none work.
Thanks for any help!
You need to install Newtonsoft.Json from Nuget packages and use Parse method from JObject:
var lastValue = JObject.Parse(currentXRPPrice.Text).SelectToken("last").ToString();
First of all, if you have Json string, you can define a class which represent this object and then you just deserialize this string to object using generic method.
var jsonString = currentXRPPrice.Text;
var deserializedResponse = JsonConvert.DeserializeObject<ReponseType>(jsonString);
var lastValue = deserializedResponse.Last;
public class ReponseType
{
...
public float Last { get; set; }
...
}
You can do it by Regex too:
var lastValue = Regex.Match(jsonString, #"last\": \"(\\d+\\.\\d+)"").Groups[0];
I have a httpWebRequest object.
It is initialised like this:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://myURL.com"); // This is actually my company URL I can't show
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
Then I want to send to this URL json datas. After tries, I figured I do it wrong, but I don't get what it is... Here is where I send it datas:
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
List<string> datas = new List<string>();
datas.Add("1");
string json = Newtonsoft.Json.JsonConvert.SerializeObject(datas);
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
It doesn't seem to be working. Is there a way to catch the URL I'm sending? I tried Fiddler, but I don't see my request.
Also this code works with a chrome console:
jQuery.ajax({
'url': 'http://myURL.com',
'type': 'POST',
'data': {data:[7]},
'success': function (data) {
console.log(data);
}
});
From the code you use at Chrome it is denoted your data structure is not correct.
First, you need a class to store the data, lets call it DataHolder:
public class DataHolder
{
public int[] data { get; set; }
}
So now you need to fill it:
var newData = new DataHolder{ data = new int[] { 1 } };
And now you can serialize it and it should work:
string json = Newtonsoft.Json.JsonConvert.SerializeObject(newData);
EDIT: as a note, in a previous question you posted you tried to send "{ data: [1] }" which is incorrect, it should be "{ \"data\": [1] }" but better stick to a class with the correct structure and let the serializer deal with those implementation details.