Unexpected character encountered while parsing value
Possibly you are not passing JSON to DeserializeObject
.
It looks like from File.WriteAllText(tmpfile,...
that type of tmpfile
is string
that contain path to a file. JsonConvert.DeserializeObject
takes JSON value, not file path - so it fails trying to convert something like @"c:\temp\fooo"
- which is clearly not JSON.
Unexpected character encountered while parsing value line 1, position 1
First, when you are using async methods you should add await keyword:
var response = await client.PostAsync(url, content);
return await response.Result.Content.ReadAsStringAsync();
Secondly, you are sending an array, so why not just try to send it and get as object not string:
var updateData = new ArrayList();
var jsonObject = JsonConvert.SerializeObject(updateData);
var content = new StringContent(jsonObject, Encoding.UTF8, "application/json");
var res = await apiClient.PutAsync(url, content);
And then in WebAPI:
[HttpPost]
public int HandleRequest([FromBody] ArrayList list)
{
return 1;
}
Message = "Unexpected character encountered while parsing value: [. Path '', line 1, position 1."
You can parse your string
to a strongly typed Model
and then de-serialize to it OR you can use dynamic
and access the properties as shown below:
You can find a working example here
using System;
using Newtonsoft.Json;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var myJsonString=@"[{'id':3,'name':'Sales'},{'id':4,'name':'PMO'},{'id':5,'name':'Research And Development'},{'id':6,'name':'Product Management'},{'id':7,'name':'HR'},{'id':8,'name':'Ava'},{'id':9,'name':'IT'}]";
var result =JsonConvert.DeserializeObject<List<Root>>(myJsonString);
Console.WriteLine("Example using Model: \n");
foreach(var item in result)
{
Console.WriteLine(item.id);
Console.WriteLine(item.name);
}
Console.WriteLine("\n");
Console.WriteLine("Example using Dynamic: \n");
//Example using dynamic
var resultDynamic=JsonConvert.DeserializeObject<dynamic>(myJsonString);
foreach(var item in resultDynamic)
{
Console.WriteLine(item["id"]);
Console.WriteLine(item["name"]);
}
}
}
public class Root
{
public int id { get; set; }
public string name { get; set; }
}
Output:
Example using Model:
3
Sales
4
PMO
5
Research And Development
6
Product Management
7
HR
8
Ava
9
IT
Example using Dynamic:
3
Sales
4
PMO
5
Research And Development
6
Product Management
7
HR
8
Ava
9
IT
Unexpected character encountered while parsing value: . Path '', line 1, position 1
To hit that default endpoint in Postman add the following in the body
"foo"
To use the following
{
"foo": "bar"
}
you would need a class like this
public class MyClass
{
public string Foo { get; set; }
}
then change the Post to
// POST api/values
[HttpPost]
public void Post([FromBody] MyClass value)
{
}
Hope that helps
Unexpected character encountered while parsing value ASP.NET Core and Newtonsoft
this works for me
Definition definition = Newtonsoft.Json.JsonConvert.DeserializeObject<Definition>(s);
classes
public partial class Definition
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("palette")]
public Palette Palette { get; set; }
}
public partial class Palette
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("default")]
public bool Default { get; set; }
[JsonProperty("swatch")]
public Swatch Swatch { get; set; }
}
public partial class Swatch
{
[JsonProperty("colors")]
public Dictionary<string,string> Colors { get; set; }
}
C# Json.net Unexpected character encountered while parsing value:
So. \u001f
means you received the byte 1F
. ‹
is in the range of extended ASCII with encoding 8B
. \b
is the ASCII backspace character with encoding 08
.
1F 8B
is the magic number for GZIP (and the 08
is the compression method: DEFLATE).
So, the server's one of the broken ones which gives you back a gzip-compressed response, even though you didn't say you could accept gzip-compressed responses.
You can tell HttpClient
to automatically decompress gzip-compressed responses:
HttpClientHandler handler = new HttpClientHandler()
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
};
using var client = new HttpClient(handler));
var httpResponseMessage = await client.GetAsync(url);
// ...
Unexpected character encountered while parsing value: <. Path '', line 0, position 0.'
You're getting the JSON parsing exception because the server is returning a text response (which you've listed in your question).
Unknown web method addEditTickets. Parameter name: methodName
Based on the error, it seems that the URL you're trying to use is invalid. Verify that the URL you're constructing is valid; it appears that functionName
does not contain the correct value in this expression:
System.Configuration.ConfigurationManager.AppSettings["links"].ToString() + functionName
ASP NET CORE with ANGULAR -"Unexpected character encountered while parsing value: a. Path '', line 0, position 0." / Error during a PUT Request
An HTTP PUT requires you to include an ID in the URI:
information/search-jobs-setbyusers/{id}
(See also https://restfulapi.net/rest-put-vs-post/)
So, you could try an HTTP POST.
The following is worth trying:
export class SearchJobsDto
{
public SearchJob: string;
}
getCompaniesSearchedByUser(searchString: string)
{
let model: SearchJobsDto = { searchString: SearchJob }
return this.http.post(this.baseUrl + "information/search-jobs-setbyusers/", model, this.httpOptions);
}
and the controller method as a POST:
[HttpPost("search-jobs-setbyusers")]
public async
Task<ActionResult<IEnumerable<GetCompaniesJobsLinksDto>>>SearchJobs(
[FromBody]SearchJobsDto searchJobsDto)
{
...
}
The error is likely due to one or both of these:
Passing an Any type parameter for the model which would give the
parsing error when resolving binding of the parameter type to the type of the model parameter in the API controller method. An explicit type for the parameter passed in the POST/PUT model is best practice.Not including an ID for the HTTP PUT with the model payload parameter.
Related Topics
How to Upload File to Server With Http Post Multipart/Form-Data
How to Ignore Convert to Nullable in Lambda Expressions
How to Remove Empty Lines from a Formatted String
Pass Array into ASP.NET Core Route Query String
How to Split Json String in C# and Store in Separate Variables
Use Linq to Collaps Multiply Collections into One Collection
Moq - Verify Exception Was Thrown
Generating Aes 256 Bit Key Value
Microsoft Azure: How to Create Sub Directory in a Blob Container
How to Convert Word Files to Pdf Programmatically
Check If Datetime Is a Weekend or a Weekday
How to Disable Uwp App Suspension
Asp.Net Core Form Post Results in a Http 415 Unsupported Media Type Response
Restsharp Post Request - Body With X-Www-Form-Urlencoded Values
How to Trim All Elements in a List
How to Get Cookies Info Inside of a Cookiecontainer (All of Them, Not for a Specific Domain)
How to Set Shadow Effect on Imageview
The Incoming Request Has Too Many Parameters. the Server Supports a Maximum of 2100 Parameters