I am using Sql Database rest api via c# code.
I am looking for a way to added the json to the body.
This is the format required.
{
"properties":
{
"startIpAddress": "0.0.0.3",
"endIpAddress": "0.0.0.3"
}
}
link. https://learn.microsoft.com/en-us/rest/api/sql/firewallrules/createorupdate
I'n not so used to doing this type procedure.
So, do I need to add the root 'properties' in the call? If so, how do I nest the json into the code?
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(new
{
startIpAddress = ip,
endIpAddress = ip
});
streamWriter.Write(json);
}
I tried this, but got bad format error back.
Many thanks in advance
Scott
For the required output json you should have something link this as your anonymous object:
new
{
properties = new {
startIpAddress = ip,
endIpAddress = ip
}
}
Now it would have the properties as main object and inside it two properties that you need.
Related
I take from a website 24images URLs(8images and each image has 3 different sizes this is how the web API works and I cannot change it)
I get those as JSON and I parse them as shown here using newton soft JSON.
Each image URL is stored in property in the same class as its different size images
and different images are stored in other classes
so there are 8classes containing 3 properties which contains image url
I am trying to get 1image url from each class
I am trying to use reflection but since these classes has different names, it is hard to do it (for me at least)
I have came this far
PropertyInfo[] properties = typeof(Photos).GetProperties();
foreach (PropertyInfo property in properties)
{
object a = property.GetValue(mm);
//I cannot use a._1 or a._2 because it is not an instance of the class I want I also cannot convert it since the class names are not the same
}
If you are using Newtonsoft JSON library - then you can use the JObject class, it's an abstraction for any JSON object.
var uri = new Uri("Your API request URL");
using var client = new HttpClient();
var response = await client.GetAsync(uri);
var data = await response.Content.ReadAsStringAsync();
var jObject = JObject.Parse(data);
var img1 = jObject["_1"];
var img2 = jObject["_2"];
//And so on.
Please see the code below, this is how you can read properties.
Helper class to read properties
public static class Helper
{
public static void GetDataByProperty(Type photosType, object photoObject, string propertyNameToRead)
{
foreach (PropertyInfo photoProperty in photosType.GetProperties())
{
if (photoProperty.Name == propertyNameToRead)
{
foreach (var urlProperty in photoProperty.PropertyType.GetProperties())
{
Console.WriteLine(urlProperty.GetValue(photoObject));
}
}
}
}
}
Sample API data
var photos = new Photos
{
_1 = new __1() { _3 = "http://www.google3.com", _2 = "http://www.google2.com", _0 = "http://www.google0.com" },
};
Reading the data
Helper.GetDataByProperty(photos.GetType(), photos._1, "_1");
I'm struggling with creating a message from a device to the IotHub in the correct format.
I'm using the Azure Client SDK (Microsoft.Azure.Devices.Client)
For better understanding lets start with a small example, we have the following string:
var TableName = "table01";
var PartitionKey = "key01";
string messagePayload = $"{{\"tablename\":\"{TableName}\",\"partitionkey\":\"{PartitionKey}\"}}";
( Taken from the example Send device to cloud telemetry) we create an eventMessage
using var eventMessage = new Microsoft.Azure.Devices.Client.Message(Encoding.UTF8.GetBytes(messagePayload))
{
ContentEncoding = Encoding.UTF8.ToString(),
ContentType = "application/json"
};
And then send it to the Cloud:
Console.WriteLine(messagePayload);
await deviceClient.SendEventAsync(eventMessage);
Output from the writeline, which is what I wanted in the first place:
{"tablename":"table01","partitionkey":"key01"}
What I can see in the shell after following the answer about watching incoming IotHub Messages:
{
"event": {
"origin": "WinSensorTest",
"module": "",
"interface": "",
"component": "",
"payload": "{\"tablename\":\"table01\",\"partitionkey\":\"key01\"}"
}
}
The Problem is, that I want it to either look like the code below or completely without the "event" etc, just the string above.
{
"event":{
"origin":"WinSensorTest",
"module":"",
"interface":"",
"component":"",
"payload":{
"tablename":"table01",
"partitionkey":"key01"
}
}
}
Where did I go wrong, how can the payload be correct json format?
Edit:
I just tried the same in Java, with the same result. Why does this not work, or is the data seen in the shell not correctly parsed?
If you create a proper Json object first it works and also shows up correct in the shell - interestingly only for this c# project, I tried doing the same in Java on Android and the same wierd formatting stuff still happens even after making an object with gson.
For the solution:
class JsonMessage
{
public string tablename { get; set; }
public string partitionkey { get; set; }
}
And then Used JsonMessage and JsonConvert to get the desired payload.
JsonMessage newMsg = new JsonMessage()
{
tablename = "table01",
partitionkey = "key01",
};
string payload = JsonConvert.SerializeObject(newMsg);
using var eventMessage = new Microsoft.Azure.Devices.Client.Message(Encoding.UTF8.GetBytes(payload))
{
ContentEncoding = Encoding.UTF8.ToString(),
ContentType = "application/json"
};
I'm new to the REST API world. I explain my need: at a specific URL I have a raw JSON text, I would like this text to be acquired by my application and inserted later in the DB as a model I created previously through EF. C# NET-CORE 2.2.
if I wasn't clear enough, don't hesitate to ask me for more details.
Thanks in advance!
Edit:
I'm sorry if it' was unclear, I will provide more detail:
Actually, i have a JSON string downloaded from an url. I did it with the following code:
var client = new WebClient();
var jsonFull = client.DownloadString(string.Format("https://url"));
It's working fine. Now, I need to take from this string only a little part of the JSON, so i did:
using var jsonDoc = JsonDocument.Parse(jsonFull);
var jsonParsed = jsonDoc.RootElement;
var myCV = jsonParsed.GetProperty("cv");
CVE is an object of this JSON, and I succesfully take it.
Inside this object, there is another one called CV_data, so I extract this:
var myCVLE = myCV.GetProperty("CV_data_meta");
The result is a var with inside
ValueKind = Object : "{
"ID": "CV-2019",
"ASS": "cv#ms.org"
}"
Now, I have a class like that
public class CV_data_meta
{
[JsonPropertyName ("ID")]
public string ID { get; set; }
[JsonPropertyName("ASS")]
public string ASS { get; set; }
}
The question is: how i can put the value in the var myCVLE in the class CV_data_meta?
I tried with
var myCVClass = JsonSerializer.Deserialize<CV_data_meta>(myCVLE);
But I get an error.
Note: I can't deserialize all the string JSON into an object, because there are a lot of information that I don't need.
Thanks in advance all!
As I understand from your question, it follows:
You first need to create the JSON object mapping (class) that the API URL will return.
Then consume the API url like this:
var client = new WebClient();
var reply =
client.DownloadString(
string.Format("https://www.yourapi.com/yourpath?yourkey={0}", yourkey));
receive and map object with mapped class
var yourvar = JsonConvert.DeserializeObject<yourclass>(reply);
Now you have the API return mapped to a class in your application, you can do whatever you want with it, including saving to a database.
I have a Web API (POST) which accepts the input JSON and does operation over it. Due to model state binding, the request by default getting bound to the request model.
We are facing a scenario where in the received JSON is not as per the expected format. Like we are having additional key-value pairs which we want to identify and notify about it. Due to model state binding I'm not able to find the additional parameters.
I have been trying the below code but I do not get the actual request. Is there a way to get the actual request rather than the overridden request.
public override void OnActionExecuting(HttpActionContext actionContext)
{
string uri = actionContext.Request.RequestUri.ToString();
uri = uri.Substring(uri.LastIndexOf('/') + 1).ToLower();
if(uri.Contains("xxx"))
{
PartnerLoginSchema reqSchema = new PartnerLoginSchema();
JsonSchema schema = JsonSchema.Parse(reqSchema.schemaJson);
var requestInput = actionContext.ActionArguments["requestx"];// receiving overriden request
string valid = JsonConvert.SerializeObject(requestInput);
JObject jsonObj= JObject.Parse(valid);
bool testcheck = person.IsValid(schema);
}
}
Eg: Expected JSON
{
req1: "asd",
req2: "wer"
}
Input JSON Received:
{
req1:"asdf",
req2:"werr",
req3:"unwanted" // this attribute is not required and has to be identified
}
I would want to find the req3 present in the JSON by some means.
Is there a way to achieve it in ASP.NET C#?
I'm able to achieve it by reading the input JSON from HttpContext.Current.Request.InputStream
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.MissingMemberHandling = MissingMemberHandling.Error;
string req_txt;
using (StreamReader reader = new StreamReader(HttpContext.Current.Request.InputStream))
{
req_txt = reader.ReadToEnd();
}
try
{
ExpectedJsonFormat s =
JsonConvert.DeserializeObject<ExpectedJsonFormat>(req_txt,
settings); // throws expection when over-posting occurs
}
catch (Exception ex)
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, BadAndUnAuthorisedRequest("extra column"));
}
I have a Facebook reply as follows:
dynamic response = client.Get("me", new { fields = "verified, picture" });
BELOW IS THE JSON IN 'response'
{"verified":true,
"picture":{"data":{"url":"https://www.abc.com","is_silhouette":true}}}
How do I access the 'url' value in the subkey of 'picture'? Here's what I tried but it fails:
fbPicture = response["picture.data.url"].toString();
I've tried different syntax but to no avail and I've also looked around but to no avail.
Thanks in advance !
The Facebook C# SDK implements an object called JsonObject.
So the easiest would be to cast the returnvalue (in JSON) to the JsonObject.
In your case this should be something like:
<!-- language-all: C# -->
dynamic response = client.Get("me", new { fields = "verified, picture" });
string url = response.picture.data.url;
I'm not entirely sure which Json library you are using, but perhaps try this:
fbPicture = response["picture"]["data"]["url"].ToString();