Please tell me how to check which json was received.
The VK API server sends a normal response:
{
"ts": "209",
"updates": [{
"event_id": "0237692ceafd3e",
"group_id": 00000001,
"object": {
"client_info": {
"button_actions": ["text", "vkpay", "open_app", "location", "open_link", "callback", "intent_subscribe", "intent_unsubscribe"],
"carousel": true,
"inline_keyboard": true,
"keyboard": true,
"lang_id": 0
},
"message": {
"attachments": [],
"conversation_message_id": 106,
"date": 1709378417,
"from_id": 00000001,
"fwd_messages": [],
"id": 151,
"important": false,
"is_hidden": false,
"out": 0,
"peer_id": 00000001,
"random_id": 0,
"text": "Привет",
"version": 10000268
}
},
"type": "message_new",
"v": "5.199"
}
]
}
And Json with an error:
{
"failed": 1,
"ts": 30
}
In this class, I have to skip the normal Json response and leave the Json with an error.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
namespace Brusketta.src.VKModels.Json
{
internal class FailedJson
{
public int Response(string jsonString)
{
var response = 0;
Filed? filed = JsonSerializer.Deserialize<Filed>(jsonString);
if (filed?.failed != 0)
{
response = filed.failed;
}
return response;
}
}
public class Filed
{
public int failed { get; set; }
public int ts { get; set; }
}
}
When a Json response with an error arrives, everything works fine, but when a normal response arrives, I get an exception:
The JSON value could not be converted to System.Int32.
Cannot get the value of a token type string as a number.
Debugging shows an exception in the line
Filed? filed = JsonSerializer.Deserialize<Filed>(jsonString);
Maybe there is an elegant solution to my problem in C#?
Thanks.
Sort the Json objects, get their length and compare them. Check for null.
2
Answers
Try this:
If you need to convert a JsonDocument you have determined to be the right type to an actual class, use the extension method group found here:
System.Text.Json.JsonSerializer.Deserialize
Hi, if you need to check json input, please define shape of json data you care first. Let us assume you want json data which has a ‘ts’ property with number type value.
By using this library, you can write as:
To check and filter it.