JsonSerializer.Deserialize can't convert number - c#

I'm trying to convert string to object using this command:
var body = JsonSerializer.Deserialize<LoginResponse>(bodyString);
This is the LoginResponse:
class LoginResponse
{
public string Token { get; set; }
public int Expires { get; set; }
}
This is how the response looks:
{"token":"longstring","expires":1676226606506}
It throws this error:
System.Text.Json.JsonException
Message=The JSON value could not be converted to System.Int32. Path: $.expires | LineNumber: 0 | BytePositionInLine: 220.
Source=System.Text.Json
How do I fix the error and make JsonSerializer.Deserialize return an object?

You need to replace int with long, because 1676226606506 bigger then int.MaxValue

Related

Newtonsoft.Json: Invalid character after parsing property name. Expected ':' but got: ,

After the project update to .NET 6 from .NET Core 3.1 the Newtonsoft package fails to deserialize object. The error that I'm getting is :
System.Private.CoreLib: Exception while executing function: ExportOrder. Newtonsoft.Json: Invalid character after parsing property name. Expected ':' but got: ,. Path '', line 1, position 39.
var message = JsonConvert.DeserializeObject<OrderRequest>(myQueueItem);
The OrderRequest class:
public class OrderRequest
{
[JsonProperty]
public string RunId
{
get;
set;
}
}
And the myQueueItem that I'm sending is:
{
"input": "{\"06-24T07-05-35Z48\",\"IsSuccess\":true,\"Message\":\"Completed Successfully\"}"
}
Is it better idea to migrate to System.Text.JSON ?
you json is not valid, it should be
var json="{\"input\": \"06-24T07-05-35Z48\",\"IsSuccess\":true,\"Message\":\"Completed Successfully\"}";
OrderRequest orderRequest=JsonConvert.DeserializeObject<OrderRequest>(json);
string message = orderRequest.Message; //Completed Successfully
class
public class OrderRequest
{
[JsonProperty("input")]
public string Input { get; set; }
public bool IsSuccess { get; set; }
public string Message { get; set; }
}

error parsing json in asp.net mvc login project

i am fetching data from an asp.net webapi and storing it as
var token = string.Empty;
var result = resMessage.Content.ReadAsStringAsync().Result;
token = JsonConvert.DeserializeObject<string>(result);
value of result is
{
value: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6ImFkbWluIiwibmJmIjoxNjMzODY1NzE0LCJleHAiOjE2MzM4Njc1MTQsImlhdCI6MTYzMzg2NTcxNH0.2Vje7sXWw4tb_h50cR3zdI5TDIjOiWR-94_i2mH40cg",
formatters: [ ],
contentTypes: [ ],
declaredType: null,
statusCode: 200
}
the error i am getting
JsonReaderException: Unexpected character encountered while parsing value: {. Path '', line 1, position 1.
in this line
token = JsonConvert.DeserializeObject<string>(result);
i am not able to understand what is going on. i have written this code in asp.net mvc project
You're trying to deserialise a string into a string here, which won't work as they're the exact same type.
You need to deserialise string result into a concrete type, which JsonConvert.DeserializeObject should be aware of, to deserialise it as such.
This should work:
public class Data
{
public string value { get; set; }
public List<object> formatters { get; set; }
public List<object> contentTypes { get; set; }
public object declaredType { get; set; }
public int statusCode { get; set; }
}
Data token = JsonConvert.DeserializeObject<Data>(result);

Refit exception system.Text.Json.JsonReaderException: 'M' is an invalid start of a value

I am using Refit version 6.0.94. I have a .net 5.0 Api and a Blazor Server app .Net 5.0. The Api and Web app are both deployed in Linux containers. When running locally in visual studio (windows 10) I do not get the error.
The Get and Delete verbs are working fine, but the Patch and Post are failing with exception
System.Text.Json.JsonException: 'M' is an invalid start of a value.
Path: $ | LineNumber: 0 | BytePositionInLine: 0. --->
System.Text.Json.JsonReaderException: 'M' is an invalid start of a
value. LineNumber: 0 | BytePositionInLine: 0.
at System.Text.Json.ThrowHelper.ThrowJsonReaderException(Utf8JsonReader&
json, ExceptionResource resource, Byte nextByte, ReadOnlySpan`1 bytes)
in
//src/libraries/System.Text.Json/src/System/Text/Json/ThrowHelper.cs:line
280
at System.Text.Json.Utf8JsonReader.ConsumeValue(Byte marker) in //src/libraries/System.Text.Json/src/System/Text/Json/Reader/Utf8JsonReader.cs:line
1034
The Api Code is Here
[HttpPatch]
public async Task<IActionResult> PatchAsync([FromBody] Customer customer)
{
return Ok(await _service.PatchAsync(customer));
}
The Poco code as follows
namespace CustomerCare
{
public class Customer
{
[JsonPropertyName("Name")]
public string Name { get; set; }
[JsonPropertyName("Surname")]
public string Surname { get; set; }
[JsonPropertyName("Id")]
public int Id { get; set; }
[JsonPropertyName("SignupDate")]
public DateTime? SignupDate { get; set; }
}
}
Refit setup and definition
services.AddRefitClient<ICustomerService>().ConfigureHttpClient(c => c.BaseAddress = new Uri("http://myservername/api/v1"))
public interface ICustomerService
{
[Delete("/CustomerCare/")]
Task<bool> DeleteCustomer(int id);
[Patch("/CustomerCare/")]
Task<bool> PatchCustomerAsync([Body] Customer customer);
[Get("/CustomerCare/{id}")]
Task<Customer> GetCustomerByIdAsync(int id);
[Post("/CustomerCare/")]
Task PostAsync([Body] Customer customer);
}
The calling code is as follows
try
{
return await _customerService.PatchCustomerAsync(customer);
}
catch (ApiException ex)
{
var errors = await ex.GetContentAsAsync<Dictionary<string, string>>();
var message = string.Join("; ", errors.Values);
throw new Exception(message);
}

How to serialize this C# return value into a JSON object?

I have this object value that is being returned and I would like to convert it into a useful JSON object that I can inspect and manipulate. Ultimately, my goal is to validate the values of username and accessKey. But 2 things are throwing this off. Double {{ makes it invalid JSON and sauce:options can't be converted into a property in a class.
{{
"browserName": "MicrosoftEdge",
"browserVersion": "latest",
"platformName": "Windows 10",
"sauce:options": {
"username": "test",
"accessKey": "123"
}
}}
Here is what I tried:
string output = JsonConvert.SerializeObject(SauceSession.Options.ConfiguredEdgeOptions);
This SauceSession.Options.ConfiguredEdgeOptions returns that object I mentioned above.
Got this back:
Newtonsoft.Json.JsonSerializationException: 'Error getting value from 'BinaryLocation' on 'OpenQA.Selenium.Edge.EdgeOptions'.'
I also tried this as per suggestions:
var serialized = JsonConvert.SerializeObject(SauceSession.Options.ConfiguredEdgeOptions);
And got back this Newtonsoft.Json.JsonSerializationException: 'Error getting value from 'BinaryLocation' on 'OpenQA.Selenium.Edge.EdgeOptions'.'
Since you cannot fix the source, you're going to have to apply a bodge to fix the JSON, for example this will work:
var fixedJson = sourceJson.Substring(1, Json.Length - 2);
Now you should have a couple of classes to hold your data, this way you can also cope with the unusual names:
public class Root
{
public string BrowserName { get; set; }
public string BrowserVersion { get; set; }
public string PlatformName { get; set; }
[JsonProperty("sauce:options")]
public Options SauceOptions { get; set; }
}
public class Options
{
public string Username { get; set; }
public string AccessKey { get; set; }
}
And now you should be able to deserialise like this:
var root = JsonConvert.DeserializeObject<Root>(fixedJson);

Error when calling WCF function with two arguments

My WCF service have method that accepts two parameters. In object browers this method looks like
public wcfelmaservice.racun SendOrder(wcfelmaservice.order Order_Header, System.Collections.Generic.List<order_items> Order_Items)
Order_Header have two members:
public string Number { set; get; }
public string Name { set; get; }
Order_Items have these members:
public decimal Price { set; get; }
public decimal Qty { set; get; }
public string ItemName { set; get; }
Now I have to pass values from PHP to WCF service. I'm doing it on this way:
<?php
$wcfClient = new SoapClient('http://localhost:28309/Service1.svc?wsdl');
ini_set("soap.wsdl_cache_enabled", "0");
//var_dump($wcfClient->__getFunctions());
$header = new StdClass;
$header->Number="1";
$header->Name="Test d.o.o";
$item = new StdClass;
$item->Price = "10.00";
$item->Qty="5";
$item->ItemName="SomeItemName";
$paramHeader = array ('Order_Header' => $header);
$paramItems = array ('Order_Items' => $item);
$response = $wcfClient->SendOrder($paramHeader, $paramsItems);
?>
When I run this script i get error:
Fatal error: Uncaught SoapFault exception: [a:DeserializationFailed]
The formatter threw an exception while trying to deserialize the
message: Error in deserializing body of request message for operation
'SendOrder'. End element 'Body' from namespace
'http://schemas.xmlsoap.org/soap/envelope/' expected.
I have no idea what I'm doing wrong?
PHP is not my forte, but a quick search on SO and I found this: How to serialize an "Object" type in PHP to be sent to a WCF Service?. Hope that helps.

Categories