C
C#•2y ago
Meistro

Newtonsoft.Json.JsonReaderException: "Unexpected character encountered while parsing value: <. Path

Hei all, I am coding a REST API HTTP POST REQUEST, but I always get an error as soon as I start Building the Project. Might it be the way how my JSON is written ? or maybe something else ? the code:
static private void RunAsyncPost(string username, string password)
{
string url = "http://someIP/rest";

// Create the JSON request body
var requestBody = new
{
info = new
{
name = "C#testfile.js",
type = 282,
isDir = false,
desc = "",
@lock = "",
ownerName = "Some Service",
access = "WDDRWDE-PIDDS",
parentId = 234253
},
acl = new[]
{
new
{
member = "Administrator",
id = 0,
type = "USER",
access = "RWWEDSGEERLP"
}
},
keywording = new
{
maskNameOriginal = "Incoming Invoice",
fields = new
{
VENDOR_NAME = "Test_Vendor1"
}
}
};

// Serialize the JSON request body
string jsonRequestBody = JsonConvert.SerializeObject(requestBody);

// Create the HTTP client and request message
using (var httpClient = new HttpClient())
using (var requestMessage = new HttpRequestMessage(HttpMethod.Post, url))
{
// Set the authorization header
string authHeader = "Basic " + Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes($"{username}:{password}"));
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Authorization", authHeader);

// Set the content type and request body
requestMessage.Content = new StringContent(jsonRequestBody, System.Text.Encoding.UTF8, "application/json");

// Send the HTTP request and get the response
var response = httpClient.SendAsync(requestMessage).Result;

// Check the response status code
if (response.IsSuccessStatusCode)
{
// Deserialize the response body
//var responseBody = JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result);
var responseBody = JsonConvert.DeserializeObject<string>(response.Content.ReadAsStringAsync().Result);
// Do something with the response
ResponseStream = responseBody.ToString(); // output normaly in CMD but here I am using a textbox of windows Forms
}
else
{
ResponseStream = $"HTTP error {response.StatusCode}"; // output normaly in CMD but here I am using a textbox of windows Forms
}
}
static private void RunAsyncPost(string username, string password)
{
string url = "http://someIP/rest";

// Create the JSON request body
var requestBody = new
{
info = new
{
name = "C#testfile.js",
type = 282,
isDir = false,
desc = "",
@lock = "",
ownerName = "Some Service",
access = "WDDRWDE-PIDDS",
parentId = 234253
},
acl = new[]
{
new
{
member = "Administrator",
id = 0,
type = "USER",
access = "RWWEDSGEERLP"
}
},
keywording = new
{
maskNameOriginal = "Incoming Invoice",
fields = new
{
VENDOR_NAME = "Test_Vendor1"
}
}
};

// Serialize the JSON request body
string jsonRequestBody = JsonConvert.SerializeObject(requestBody);

// Create the HTTP client and request message
using (var httpClient = new HttpClient())
using (var requestMessage = new HttpRequestMessage(HttpMethod.Post, url))
{
// Set the authorization header
string authHeader = "Basic " + Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes($"{username}:{password}"));
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Authorization", authHeader);

// Set the content type and request body
requestMessage.Content = new StringContent(jsonRequestBody, System.Text.Encoding.UTF8, "application/json");

// Send the HTTP request and get the response
var response = httpClient.SendAsync(requestMessage).Result;

// Check the response status code
if (response.IsSuccessStatusCode)
{
// Deserialize the response body
//var responseBody = JsonConvert.DeserializeObject(response.Content.ReadAsStringAsync().Result);
var responseBody = JsonConvert.DeserializeObject<string>(response.Content.ReadAsStringAsync().Result);
// Do something with the response
ResponseStream = responseBody.ToString(); // output normaly in CMD but here I am using a textbox of windows Forms
}
else
{
ResponseStream = $"HTTP error {response.StatusCode}"; // output normaly in CMD but here I am using a textbox of windows Forms
}
}
Thanks in advance for any help 🙂
14 Replies
mtreit
mtreit•2y ago
It sounds like the response body is not JSON.
Meistro
MeistroOP•2y ago
Hei @mtreit do you mean this line ?

var responseBody = JsonConvert.DeserializeObject<string>(response.Content.ReadAsStringAsync().Result);

var responseBody = JsonConvert.DeserializeObject<string>(response.Content.ReadAsStringAsync().Result);
mtreit
mtreit•2y ago
Well you didn't say what line the exception happens on, so I am speculating, but yes since it's an error in the reader that seems like a possible candidate.
Meistro
MeistroOP•2y ago
Oh yes sorry, I debugged it and the error occurs at that line but the problem is, I dont know what to do
Meistro
MeistroOP•2y ago
Meistro
MeistroOP•2y ago
maybe its better to see the code this way
pip
pip•2y ago
you're mostly getting some sort of unauthorized error from the API. that code looks mostly fine(obviously there's some improvements but i won't go into them) do a Console.WriteLine on the result before deserializing make sure its valid json
mtreit
mtreit•2y ago
Yes, you're probably getting HTML back instead of JSON. Print it out and see what it says.
Meistro
MeistroOP•2y ago
ok thank you very much. but how do I deserialize it then if this way doesnt work ? I will give you a feed back as soon as I an output from Console
pip
pip•2y ago
if you're getting HTML back from the API, then that means you just have to make sure your request is valid. when your request is valid you will get valid json back validity can be determined by = the info you send in your request, your api keys, the URL you're using for the request etc.
Meistro
MeistroOP•2y ago
Hei hei, me again. Thank you for the response. I have tryed the console output now and it gave me this
--------------Post---------------------
<!doctype html>
<html>
<head>
<!-- Important: rapi-doc uses utf8 charecters -->
<meta charset="utf-8">
<script src="js/rapidoc-min.js"></script>
<style>
pre.multiline {max-height: 66vh;}
</style>
</head>
<body>
<rapi-doc spec-url="./v3/api-docs" show-header="true" allow-spec-file-load="false">
<img slot="logo" src="elologo.png" />
</rapi-doc>
</body>
</html>
--------------Post---------------------
<!doctype html>
<html>
<head>
<!-- Important: rapi-doc uses utf8 charecters -->
<meta charset="utf-8">
<script src="js/rapidoc-min.js"></script>
<style>
pre.multiline {max-height: 66vh;}
</style>
</head>
<body>
<rapi-doc spec-url="./v3/api-docs" show-header="true" allow-spec-file-load="false">
<img slot="logo" src="elologo.png" />
</rapi-doc>
</body>
</html>
lol it worked because a file has been created on server
{"guid":"(A7CB8DE0-C067-E222-4D8A-56C544D67D61)","id":11583,"name":"testDatei.js"}
{"guid":"(A7CB8DE0-C067-E222-4D8A-56C544D67D61)","id":11583,"name":"testDatei.js"}
but the deserialize doenst work
pip
pip•2y ago
hehe
pip
pip•2y ago
How to serialize and deserialize JSON using C# - .NET
Learn how to use the System.Text.Json namespace to serialize to and deserialize from JSON in .NET. Includes sample code.
Accord
Accord•2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server