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\"}}"
Related
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.
I have an Attachments json array in the request payload, and each attachment has three properties:
Name - string and holds the name of the file to be attached.
ContentType - System.Net.Mime.ContentType and holds the mediatype info of the file and
FileData - string and holds base64encoded string of contents of the file/attachment.
Whenever ContentType is null/empty I see that the control does not even hit the controller, but the API is sending a 500 internal server error, and the error message in the response is not helpful for the client:
Message: This property cannot be set to an empty string. (Parameter 'value')
Is there a way to let the API pass through whatever value is entered for this property(mediaType in ContentType) and I would like to do the validation in the API for this property and throw a 400 with a proper message. Below is the request body that is causing above error:
"Attachments": [
{
"Name": "Something.txt",
"ContentType": {
"Boundary": null,
"CharSet": null,
"MediaType": "", //this is causing the above error and I would like this one to be a bad request not a internal server error.
"Name": "SampleContentType",
"Parameters": [
{
"Key": "name",
"Value": "SampleContentType"
}
]
},
"FileData": "some base64 encoded string here"
}
]
One solution to this is to use a custom ContentType model which mimics the one being used, do the validation then map it to the original one, but I want to understand why the API is throwing 500, before it even hits the controller.
Use the ConsumesAttribute to let the framework check it.
[Consumes("multipart/form-data")] // example
public async Task<IActionResult> MyAction { ... }
This will return a 415 by default if the Consumes criteria is not met.
I am trying to make a message handler for received JSON strings over MQTT. I have this working for one type of message.
Here is my code:
static void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
// handle message received
Console.WriteLine("Received = " + Encoding.UTF8.GetString(e.Message) + " on topic " + e.Topic);
string source = Encoding.UTF8.GetString(e.Message);
dynamic data = JObject.Parse(source);
Console.WriteLine(data.content.value);
// this data.content.value is working for message 1 but crashes for message 2
}
How can I avoid using a lot of try catches in my message handler in case I have 2 (or more) different MQTT messages entering?
These are my 2 types of messages for now:
/// message 1:
{
"header": {
"headeritem": "exampleheader",
"type": "headertype",
"info": "headerinfo"
},
"content": {
"name": "contentname",
"value": true
}
}
/// message 2:
{
"header": {
"headeritem": "exampleheader",
"type": "headertype",
"info": "headerinfo"
},
"content": {
"item1": "exampleitem1",
"item2": "exampleitem2",
"item3": [
{
"item3type1": "exampletype1.1",
"item3type2": "exampletype2.1",
"item3type3": "exampletype3.1",
"item3type4": ["0xFFAA"]
},
{
"item3type1": "exampletype1.2",
"item3type2": "exampletype2.2",
"item3type3": "exampletype3.2",
"item3type4": ["0xFFBB"]
},
{
"item3type1": "exampletype1.3",
"item3type2": "exampletype2.3",
"item3type3": "exampletype3.3",
"item3type4": ["0xFFCC"]
}
]
}
}
When you do not know what JSON type is comming in, you can use reflection on the dynamic data type to check if the property exists.
Like explained here:
Test if a property is available on a dynamic variable
However, when the different JSON formats are limited to only a few, maybe you are better off creating hard typed classes to parse the JSON in.
Like explained here:
How to Convert JSON object to Custom C# object?
This way you do not have to worry about whether a property exists.
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");
I have an C# program which calls a website API to get a JSON response:
{"success":true, "taskid":"1466687729433", "tasktype":"kkk", "steamid":32323, "value":5.68, "token":"sadsad", "items":[5751210424, 5751210304], "botid":1}
Then I'm using it like this:
public Task checkForTasks()
{
try
{
return JsonConvert.DeserializeObject<Task>(base.Bot.SteamWeb.Fetch("LinkHere", "GET", null, false, ""));
}
catch (Exception)
{
}
return new Task { success = false };
}
But I keep getting error in my output console:
Exception thrown: 'Newtonsoft.Json.JsonReaderException' in
Newtonsoft.Json.dll
What could cause that?
It is not a valid json:
{"success":true, "taskid":"", "tasktype":"", "steamid":, "value":, "token":"", "items":[5751210424, 5751210304], "botid":}
try with something like:
{"success":true, "taskid":"", "tasktype":"", "steamid":, "value":"", "token":"", "items":[5751210424, 5751210304], "botid": 1}
Well I copy your json to my visual studio with special paste it gives me error while generating relevant class
Your JSON is invalid.
{
"success": true,
"taskid": "",
"tasktype": "",
"steamid": ,
"value": ,
"token": "",
"items": [5751210424, 5751210304],
"botid":
}
value and botid are missing. The deserializer cannot deserialize incomplete JSON.