C# GetValue from JSON - c#

I have a NodeJS Server and a C# Unity Client. The NodeJS server sends an object to the C# client.
SERVER
var obj = new Object();
obj.name = data.name;
obj.position = data.position;
var jsonString= JSON.stringify(obj);
C# Client
try
{
Debug.Log(response.ToString()); // WORKS the result is
/*
[
{
"name": "Peter",
"position": "(13.6, 1.5, 2.3)"
}
]
*/
Debug.Log(response.GetValue(1).ToString()); // Don't work, receive in console (ERROR).
}
catch
{
Debug.Log("Error");
}
Output
[
{
"name": "Peter",
"position": "(13.6, 1.5, 2.3)"
}
]
So I try to read the JSON to get the Value Name and Position.
I have already tried the following:
string resVal1 = response.GetValue<string>();
Enemy resVal2 = response.GetValue<Enemy>(1);
string enemyName= response.GetValue(1).Value<string>("name");
Source:
https://github.com/doghappy/socket.io-client-csharp
I also only get "Error" here. What am I doing wrong? How do I get name and position from the JSON string. I have not much experience with JSON.

The JSON returned is an array with a single element, that element is an object with 2 properties - one of which is name so I suspect he correct code to read that would be:
string enemyName= response.GetValue(0).Value<string>("name");

Related

C# Firestore API POST - Cannot find field

I have hit a bit of a brick wall here. I am working in client side c# code and using the firestore API. I cannot post a document (with data) in. I am able to create a document by removing the line ".AddJsonBody(testdata)" below.
CODE
string url = "https://firestore.googleapis.com/v1/projects/<MYPROJECT>/databases/(default)/documents/Users";
var client = new RestClient(url);
string testdata = "{\"foo\":\"bar\"}";
var request = new RestRequest()
.AddJsonBody(testdata);
var response = await client.ExecutePostAsync(request);
ERROR
{
"error": {
"code": 400,
"message": "Invalid JSON payload received. Unknown name "foo" at 'document': Cannot find field.",
"status": "INVALID_ARGUMENT",
"details": [
{
"#type": "type.googleapis.com/google.rpc.BadRequest",
"fieldViolations": [
{
"field": "document",
"description": "Invalid JSON payload received. Unknown name "foo" at 'document': Cannot find field."
}
]
}
]
}
}
I have tried using document:commit. I have tried various different methods of parsing the data, all keep getting similar errors.

How to access Json (which was a result of HttpMessage) in C#?

I am writing two applications (Web API's) in .NET . From the app A I want to call a method in Controller of app B using Http Request.
Here
using (var askPensionerDetails = new HttpClient())
{
double pensionToDisburse = 0;
askPensionerDetails.BaseAddress = new Uri("http://localhost:55345/api/pensionerdetails/");
var responseTask = askPensionerDetails.GetAsync("getById?pan=" + inputOfPensioner.PAN);
responseTask.Wait();
var result =responseTask.Result ;
if (result.IsSuccessStatusCode)
{
var readTask = result.Content.ReadFromJsonAsync<object>();
readTask.Wait();
return Ok(readTask.Result);
}
}
The output for this in postman is
{
"name": "bunk seenu",
"dateOfBirth": "1990-01-02T00:00:00",
"pan": "ABCD12351E",
"salaryEarned": 45000,
"allowances": 500,
"pensionType": 1,
"bankDetails": {
"bankName": "SBI",
"accountNumber": "SBI00001BS",
"bankType": 0
}
}
That was a desired output. But the problem is how to access the properties like bankdetails,name,pan,salaryEarned.
I have tried using readTask.Result["name"] but it is throwing error.
I have also tried using result.Content.ReadAsStringASync();
But the output in postman is
{
"name": [],
"dateOfBirth": [],
"pan": [],
"salaryEarned": [],
"allowances": [],
"pensionType": [],
"bankDetails": [
[
[]
],
[
[]
],
[
[]
]
]
}
I don't have class associated with the result type of Json for statement readTask = result.Content.ReadFromJsonAsync(); (As per design constraints).
From the docs:
If you have JSON that you want to deserialize, and you don't have the class to deserialize it into, you have options other than manually creating the class that you need:
Deserialize into a JSON DOM (document object model) and extract what you need from the DOM.
The DOM lets you navigate to a subsection of a JSON payload and deserialize a single value, a custom type, or an array. For information about the JsonNode DOM in .NET 6, see Deserialize subsections of a JSON payload. For information about the JsonDocument DOM, see How to search a JsonDocument and JsonElement for sub-elements.
Use the Utf8JsonReader directly.
Use Visual Studio 2019 to automatically generate the class you need:
Copy the JSON that you need to deserialize.
Create a class file and delete the template code.
Choose Edit > Paste Special > Paste JSON as Classes. The result is a class that you can use for your deserialization target.
You can use Newtonsoft.Json
JObject jo = JObject.Parse(readTask.Result);
var name = jo["name"];
if(string.IsNnullOrEmpty(name)){
///some code
}

Asp.net Mvc receives a complex object as a list of key/value pair array

I have two asp.net mvc apps that am trying to get to communicate with each other by sending a complex serialized object from one of the app to the other.
But when the data reaches the other end, the object comes in as a list of array of key-value pair. Below are the details of the what am trying to send/recieve.
Here is the code that am using to send the json object
using (var hc = new HttpClient())
{
hc.DefaultRequestHeaders.Accept.Clear();
hc.DefaultRequestHeaders.Accept.Add(Media);
var dict = new Dictionary<string, DejaVuObject> {{"Entity", obj}};
var strinified = JsonConvert.SerializeObject(dict);
var stringContent = new StringContent(strinified, Encoding.UTF8, "application/json");
var response = await hc.PostAsync(url, stringContent);
return response;
}
The receiving method signature
[HttpPost]
public ActionResult RecieveEntity(Dictionary<string, object> post)
Here is what am sending
{
"Main Service ID": "1",
"Node ID": "",
"Parameters": [
{
"Name": "firstname",
"Validation": {
"Entity": 0,
"EntityListFilter": "",
"IsNotEditable": false,
"IsPrimaryIdentifier": false,
"IsRequired": true,
"IsUnique": false,
"Parameter Format": 0,
"ParameterMode": ""
}
}
],
"CustomEvents": [
{
"Description": "event description",
"Message": "new message",
"MilestoneCondition": "milestone information.",
"Name": "new message",
"TheFields": []
}
],
"Processings String": "Action failed.[TN01-31:Action failed]"
}
Here is what am receiving
{
"Processings String": "Action failed.[TC01-71:Action failed while processing the request.]::Action succeeded.[TC01-54:Processing this command was successful.]",
"Parameters": "[Name, Firstname][Validation, ][Key, 2e431711-2ba9-40ef-985e-dbfa8c13a932][isrequired, True][fieldname, ][Name, Lastname][Validation, ][Key, be4de2d6-d39e-44fa-8f31-b4b0964f82da]",
"CustomEvents": "[Description, Processing this command was successful][Message, Action suceeded][MilestoneCondition, When command processing suceeds.][Name, Action suceeded][TheFields, System.Collections.Generic.List`1[System.Dynamic.DejaVuObject]]",
"Main Service ID": "1"
}
If you look properly in what comes into the other system, you will find that the of most of the inner object is an array of key/value pair instead of ordinary array of objects that was sent. What am I doing wrong, and how do i go about correcting it?
Its the fact that you're using a dictionary type to receive the content. At the point the data packet is sent from the app1 its as per your definition. So updating app1 isn't going to help you.
As #Krishna has suggested update the signature to use dynamic, or you can extend your current app2 method to deal with the new interface.
Do you have an example of the data packet from one of the existing integrated apps?

Valid JSON string throws Unexpected character encountered error

I'm trying to connect an angular2 client to a C# ASP.net core server. When I'm sending a JSON string using websockets from the client to the server, I get an error:
Unexpected character encountered while parsing value: {. Path 'Argument', line 1, position 39.
The JSON string is as follows (The error seems to originate from the opening bracket after "Argument:"):
{
"MethodName": "CreateUser",
"Argument": {
"User": {
"Attributes": [{
"Name": "age",
"Value": "30",
"Type": 0
}],
"Email": "test#mail.com",
"Name": "Test Name"
},
"Password": "1234"
}
}
The code that throws the error is here:
public string Receive(string input)
{
try
{
Debug.WriteLine(input);
InstructionServer jsonObject = JsonConvert.DeserializeObject<InstructionServer>(input); // This fails
string methodName = jsonObject.MethodName;
string data = jsonObject.Argument;
return methods[methodName](1, data, "", "");
}
catch (Exception e)
{
return "error: " + e.Message;
}
}
I can't seem to figure out what the error is, because when I throw the JSON into an online JSON Formatter, it reports it as valid JSON. Any help would be appreciated.
EDIT: Just to clarify on the valid JSON. I tried printing the json string out before sending it on the client and after receiving it on the server, and it is the same json string as written above.
Argument appears to be expecting a string, but found an object. You'll have to check the format that InstructionServer is expecting and ensure that it will be able to deserialize correctly.
The Receive method expect the string value, this means you have to convert your object to JSON format to be like this:
"{\"MethodName\":\"CreateUser\",\"Argument\":{\"User\":{\"Attributes\":[{\"Name\":\"age\",\"Value\":\"30\",\"Type\":0}],\"Email\":\"test#mail.com\",\"Name\":\"Test Name\"},\"Password\":\"1234\"}}"

Deserialize JSON response with unknown object names using c# ReadObject()

So i'm trying to deserialise a JSON response implicitly back into a object instance using the following code.
DataContractJsonSerializer jsonSerialiser = new DataContractJsonSerializer(responseType);
responseBase = jsonSerialiser.ReadObject(responseStream);
The response if piped out as a string looks as follows
{
"20170317112739": {
"start": {
"SQ": 4577,
"TS": "2017-03-17T11:26:59",
"FisCode": "_R1-AT1_001/1_SQ4577_2017-03-17T11:26:59_0,00_0,00_0,00_0,00_0,00_vr1zl86Y_49e862eb_rNvvLM3FKh4=_DGZt+z+A3fY8zLlt2E55R8zCD/wf7yw9q/VivAiaNtxNpaTkhlTONAsD6yc+8Vcxwnm/lBalIwEI6GswC04kqg=="
},
"close": {
"SQ": 4667,
"TS": "2017-03-17T11:27:39",
"FisCode": "_R1-AT1_001/1_SQ4667_2017-03-17T11:27:16_0,00_0,00_0,00_0,00_0,00_r/82sV+w_49e862eb_FD/gDnivnes=_LKmvkk5OEoL7EFIebQU73VDVfPGzRGOyKNLlIW1mJkvPpqS0oVdWmqiNGR0cnpT35ArF++XzO1D/q7keTJe4cA=="
}
},
"current": {
"start": {
"SQ": 4670,
"TS": "2017-03-17T11:27:39",
"FisCode": "_R1-AT1_0/1_SQ4670_2017-03-17T11:27:39_0,00_0,00_0,00_0,00_0,00_/agx6rsw_49e862eb_qTh1/lCawvo=_f7yNP/+WUWZCojerZ9fe/wID1gll0I37swEKsauV8h7g8gSCFZ2Ykg45JjkO7BrChCBkl0ewohuGdbP4haLbrQ=="
},
"2017-03": {
"SQ": 4673,
"TS": "2017-03-17T11:27:39",
"FisCode": "_R1-AT1_0/1_SQ4670_2017-03-17T11:27:39_0,00_0,00_0,00_0,00_0,00_/agx6rsw_49e862eb_qTh1/lCawvo=_f7yNP/+WUWZCojerZ9fe/wID1gll0I37swEKsauV8h7g8gSCFZ2Ykg45JjkO7BrChCBkl0ewohuGdbP4haLbrQ=="
}
},
"lic": "0SvXs"
}
Simple responses from the JSON service are no problem i can simply decorate these with [DataContract] and [DataMember].
The problem with this particular service response is that item names such as "2017-03" will change depending on when the call is made to during other months/years.
How do i deal with this in C#?, can someone supply an example of how my class should look?
For the life of me i cannot get this data into my object class!
You can have a dynamic dictionary as suggested in this post Deserialize JSON into C# dynamic object?
Or you can implement something like this with the help of System.Web.Helpers
using (StreamReader r = new StreamReader("sample.json"))
{
string json = r.ReadToEnd();
dynamic data = Json.Decode(json);
Console.WriteLine(data["20170317112739"].start.sq);
}
Here sample.json contains your sample JSON response.

Categories

Resources