What would be my next step to take? I want to be able to write the block with the id value of ex 1. Or the block with ex GPIO value 3 with something simple as maybe WriteLine(id1) Relay.cs
public class Relay
{
public int GPIO { get; set; }
public int id { get; set; }
public int status { get; set; }
public string type { get; set; }
}
Program.cs
static void Main(string[] args)
{
var client = new RestClient("http://192.168.0.3:1337/auto/api/v1.0/");
var request = new RestRequest("relays", Method.GET);
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
var response = client.Execute<Relay>(request);
Console.WriteLine(response.Content);
Console.ReadLine();
}
and my array on 192.168.0.3:1337/auto/api/v1.0/relays
{
"relays": [
{
"GPIO": 2,
"id": 1,
"status": 0,
"type": "Relay"
},
{
"GPIO": 3,
"id": 2,
"status": 0,
"type": "Relay"
}
]
}
I'm sorry if anything is unclear, or if the answer is simple. If I missed to include something important, just point it out and I'll post it!
you can deserialize it in List of Relay and iterate and read any value you want
static void Main(string[] args)
{
var client = new RestClient("http://192.168.0.3:1337/auto/api/v1.0/");
var request = new RestRequest("relays", Method.GET);
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
var response = client.Execute<Relay>(request);
JavaScriptSerializer ser = new JavaScriptSerializer();
var relayList = ser.Deserialize<List<Relay>>(response.Content);
foreach(Relay relay in relayList)
Console.WriteLine(relay.ID);
Console.ReadLine();
}
You need to parse that JSON into objects to manipulate them, and it seems that your REST client already does it, just need to pass the correct type.
1-Create the class structure like the structure you're receiving:
public class Relay
{
public int GPIO { get; set; }
public int id { get; set; }
public int status { get; set; }
public string type { get; set; }
}
public class RelayCollection
{
public Relay[] relays { get; set; }
}
2-Parse the received json:
var relayCollection = client.Execute<RelayCollection>(request);
Now you have all the relays inside relayCollection.relays, manipulate them as any other array/class
Beforehand I apologize for my English, but you can serialize a json by creating a list of your class and then deserialize the json like this:
public class Relay {
int GPIO;
public int gPIO {get {return GPIO;} set {GPIO=value;}}
int Id;
public int ID {get {return Id;} set {Id = value;}}
int Status;
public int status {get {return Status;} set {Status = value;}}
string Type;
public string type {get {return Type;} set {Type = value;}}
}
Now create a class list
List<Relay > relayList = new List<Relay >();
And finally deserealize the json
relayList = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Relay>>(request);
Related
I have a json file and I want to deserialize it into an object, however, for this I need the value parameter of the method: JsonConvert.DeserializeObject<Parametros>(parameter)
I don't know how to get it, I tried to convert it to JObject but it didn't work, any ideas?
My code so far:
IConfiguration configuration = GetConfigurationFromJson();
JObject json = JObject.Parse(JSON_FILE_PATH);
Parametros parametros = JsonConvert.DeserializeObject<Parametros>(json); //Wrong parameter
{
"boletinConfig": {
"nBoletin": "00030000",
"claveSancion": 502,
"agente": 660050
}
}
public class Parametros
{
public string nBoletin { get; set; }
public int claveSancion { get; set; }
public int agente { get; set; }
public Parametros(string nBoletin, int claveSancion, int agente)
{
this.nBoletin = nBoletin;
this.claveSancion = claveSancion;
this.agente = agente;
}
public Parametros()
{
}
}
It should be like this.
using Newtonsoft.Json;
string jsonTextFromFile = File.ReadAllText(JSON_FILE_PATH);
var parametrosObject = JsonConvert.DeserializeObject<Parametros>(jsonTextFromFile);
You don't need JObject at all.
var jsonString = File.ReadAllText(**Path to File**);
Parameters result = JsonConvert.DeserializeObject<Parameters>(jsonString);
I try to deserialize my JSON Response which is at below, but when i print the content of each parameter, it shows error.
My JSON Resposne:
[
{
"faceRectangle": {
"top": 214,
"left": 472,
"width": 450,
"height": 450
},
"faceAttributes": {
"age": 19.0,
"emotion": {
"anger": 0.0,
"contempt": 0.0,
"disgust": 0.0,
"fear": 0.0,
"happiness": 0.0,
"neutral": 0.996,
"sadness": 0.003,
"surprise": 0.001
}
}
}
]
I able to deserialize my code with this:
public static async Task<List<RootObject>> MakeAnalysisRequest(string imageFilePath)
{
HttpClient client = new HttpClient();
// Request headers.
client.DefaultRequestHeaders.Add(
"Ocp-Apim-Subscription-Key", subscriptionKey);
// Request parameters. A third optional parameter is "details".
string requestParameters = "&returnFaceId=false&returnFaceLandmarks=false&returnFaceAttributes=age,emotion";
// Assemble the URI for the REST API Call.
string uri = uriBase + "?" + requestParameters;
HttpResponseMessage response;
// Request body. Posts a locally stored JPEG image.
byte[] byteData = GetImageAsByteArray(imageFilePath);
using (ByteArrayContent content = new ByteArrayContent(byteData))
{
// This example uses content type "application/octet-stream".
// The other content types you can use are "application/json"
// and "multipart/form-data".
content.Headers.ContentType =
new MediaTypeHeaderValue("application/octet-stream");
// Execute the REST API call.
response = await client.PostAsync(uri, content);
// Get the JSON response.
string contentString = await response.Content.ReadAsStringAsync();
// Display the JSON response.
Console.WriteLine("\nResponse:\n");
string format = JsonPrettyPrint(contentString);
var deserializedJson = JsonConvert.DeserializeObject<List<RootObject>>(format);
Console.WriteLine(format);
Console.WriteLine(deserializedJson);
Console.WriteLine("\nPress Enter to exit...");
return deserializedJson;
}
}
But when i try to print each parameter value, it shows error:
var output1 = MakeAnalysisRequest(imageFilePath).Result;
var x= output1[0].FaceAttributes.Emotion.Anger;
Console.WriteLine(x);
var y = output1[1].FaceAttributes.Emotion.Neutral;
Console.WriteLine(y);
if (x >= 0.5)
{
System.Media.SoundPlayer player = new System.Media.SoundPlayer(#"D:\Degree course outline\FYP2019\soft.wav");
player.Play();
}
if (y>= 0.5)
{
System.Media.SoundPlayer player = new System.Media.SoundPlayer(#"D:\Degree course outline\FYP2019\soft.wav");
player.Play();
}
My error code is like this:
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
How could i solve it?
Thanks
My class object:
class Program
{
public class FaceRectangle
{
public int Top { get; set; }
public int Left { get; set; }
public int Width { get; set; }
public int Height { get; set; }
}
public class Emotion
{
public double Anger { get; set; }
public double Contempt { get; set; }
public double Disgust { get; set; }
public double Fear { get; set; }
public double Happiness { get; set; }
public double Neutral { get; set; }
public double Sadness { get; set; }
public double Surprise { get; set; }
}
public class FaceAttributes
{
public double Age { get; set; }
public Emotion Emotion { get; set; }
}
public class RootObject
{
public FaceRectangle FaceRectangle { get; set; }
public FaceAttributes FaceAttributes { get; set; }
}
Try this code:
var output1 = await MakeAnalysisRequest(imageFilePath);
if (output1 != null && output1.Count > 0)
{
var x= output1[0].FaceAttributes.Emotion.Anger;
Console.WriteLine(x);
}
if (output1 != null && output1.Count > 1)
{
var y = output1[1].FaceAttributes.Emotion.Neutral;
}
The out of range exception is there because your deserialized output does not have enough elements to access. Please share your class object for more help.
Also try to avoid using the .Result to get the return value from asynch as it could lead to deadlocks.
Edit after providing class
With your class being like this then change your code accordingly:
var output1 = await MakeAnalysisRequest(imageFilePath);
if (output1 != null && output1.Count > 0)
{
var x= output1[0].FaceAttributes.Emotion.Anger;
Console.WriteLine(x);
var y = output1[0].FaceAttributes.Emotion.Neutral;
Console.WriteLine(y);
}
There is only one RootObject in your jsons array that is comprised of two others.
Json array [] object {}
An array with two objects looks like this [{},{}] and not like this [{{},{}}]
I want to send Post Request with C# WebClient with this Json Schema :
[
{
"id": "00000000-0000-0000-0000-000000000000",
"points": [
{
"timestamp": "2017-12-04T16:07:44.562Z",
"value": 0
}
]
}
]
I've tried This :
public class RequestData
{
public string id {get; set; }
public points points { get; set; }
}
public class points
{
public DateTime timestamp { get; set; }
public float value { get; set; }
}
My Program :
Random number = new Random();
var req = new RequestData();
req.id = "0e13d9c-571c-44f4-b796-7c40c0e20a1d";
req.points = new points { timestamp = DateTime.UtcNow, value =
number.Next(100, 99999) };
JsonSerializerSettings settings = new JsonSerializerSettings();
var data = JsonConvert.SerializeObject(req);
WebClient client = new WebClient();
client.Headers.Add(HttpRequestHeader.Authorization,
AquaAtuhorization.accessToken);
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
client.UploadString ("http://localhost:8080/api/v1/data/writeNumericValues",
data );
And I always get Http 415 (Unsupported Media Type).
How could I format my C# Object as the restApi accepeted Format.
Look at the JSON, the square brackets [ ] denote that something is an array. In this case both RequestData and points have to be an array, see the example below:
public class RequestData
{
public string id { get; set; }
public List<points> points { get; set; } // I use list, could be an array
}
public class points
{
public DateTime timestamp { get; set; }
public float value { get; set; }
}
Then construct your req object like this:
var req = new List<RequestData> // Again I use list, could be an array
{
new RequestData
{
id = "0e740d9c-571c-44f4-b796-7c40c0e20a1d",
points = new List<points> // Defined as a list, even though it has one entry
{
new points
{
timestamp = DateTime.UtcNow,
value = number.Next(100, 99999)
}
}
}
};
Then just serialize it as normal, the result will be the below:
[
{
"id":"0e740d9c-571c-44f4-b796-7c40c0e20a1d",
"points":[
{
"timestamp":"2017-12-04T17:12:25.8957648Z",
"value":59522.0
}
]
}
]
Your Json class needs to be like this, see http://json2csharp.com/ or use paste as JSON from VS https://blog.codeinside.eu/2014/09/08/Visual-Studio-2013-Paste-Special-JSON-And-Xml/
public class Point
{
public DateTime timestamp { get; set; }
public int value { get; set; }
}
public class RootObject
{
public string id { get; set; }
public List<Point> points { get; set; }
}`
How can I deserialize JSON to a list using DeserializeObject and JsonProperty while the indexes of the elements are non-integer?
JSON:
{
"success": true,
"TEST": {
"360450323_188530139": {
"id": "24216",
"name": "zxc",
"desc": "cxz"
},
"310777518_0": {
"id": "6458678634",
"name": "dfgsfd",
"desc": "sdfxcvnbhr"
}
}
}
Is there any way to make a list from that?
I've tried:
using(WebClient wc = new WebClient())
{
var url = "...";
var json = wc.DownloadString(url);
Result result = JsonConvert.DeserializeObject<Result>(json);
}
public class Result
{
[JsonProperty("success")]
public string Success { get; set; }
[JsonProperty("TEST")]
public List<Test> Tests{ get; set; }
}
public class Test
{
[JsonProperty("id")]
public int id { get; set;}
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("desc")]
public string Desc { get; set; }
}
You have a keyed collection in the JSON, which maps easily to a dictionary. You could examine result.Test.Values
using(WebClient wc = new WebClient())
{
var url = "...";
var json = wc.DownloadString(url);
Result result = JsonConvert.DeserializeObject<Result>(json);
// result.Values should contain the Test instances at this point.
}
public class Result
{
[JsonProperty("success")]
public string Success { get; set; }
[JsonProperty("TEST")]
public Dictionary<string,Test> Tests{ get; set; }
}
public class Test
{
// omitted - same as in question.
}
How to connect to XML-RPC Api from c# ,
A client can interact with a Pandorabot by POST'ing to:
http://www.pandorabots.com/pandora/talk-xml
The form variables the client needs to POST are:
botid - see H.1 above.
input - what you want said to the bot.
custid - an ID to track the conversation with a particular customer. This variable is optional. If you don't send a value Pandorabots will return a custid attribute value in the element of the returned XML. Use this in subsequent POST's to continue a conversation.
How to call?
This should get you going:
public void Talk()
{
string xmlResult = null;
Result result = null; // Result declared at the end
string botId = "c49b63239e34d1"; // enter your botid
string talk = "Am I a human?";
string custId = null; // (or a value )
using (var wc = new WebClient())
{
var col = new NameValueCollection();
col.Add("botid", botId);
col.Add("input", talk);
if (!String.IsNullOrEmpty(custId))
{
col.Add("custid", custId);
}
byte[] xmlResultBytes = wc.UploadValues(
#"http://www.pandorabots.com/pandora/talk-xml",
"POST",
col);
xmlResult = UTF8Encoding.UTF8.GetString(xmlResultBytes);
result = Result.GetInstance(xmlResultBytes);
}
//raw result
Console.WriteLine(xmlResult);
// use the Result class
if (result.status == 0) // no error
{
Console.WriteLine("{0} -> {1}",
result.input, result.that);
}
else // error
{
Console.WriteLine("Error: {0} : {1}",
result.input, result.message);
}
}
[XmlRoot(ElementName="result")]
public class Result
{
static XmlSerializer ser = new XmlSerializer(typeof(Result) , "");
public Result()
{
}
public static Result GetInstance(byte[] bytes)
{
return (Result)ser.Deserialize(new MemoryStream(bytes));
}
[XmlAttribute]
public int status { get; set; }
[XmlAttribute]
public string botid { get; set; }
[XmlAttribute]
public string custid { get; set; }
[XmlElement]
public string input { get; set; }
[XmlElement]
public string that { get; set; }
[XmlElement]
public string message { get; set; }
}