program story

값을 구문 분석하는 동안 예기치 않은 문자가 발견되었습니다.

inputbox 2020. 9. 7. 08:06
반응형

값을 구문 분석하는 동안 예기치 않은 문자가 발견되었습니다.


현재 몇 가지 문제가 있습니다. Json.NET에서 C #을 사용하고 있습니다. 문제는 내가 항상 얻는 것입니다.

{ "값을 구문 분석하는 동안 예기치 않은 문자가 발견되었습니다. e. 경로 '', 줄 0, 위치 0."}

그래서 Json.NET을 사용하는 방법은 다음과 같습니다. 저장해야 할 클래스가 있습니다. 클래스는 다음과 같습니다.

public class stats
{
    public string time { get; set; }
    public string value { get; set; }
}

public class ViewerStatsFormat
{
    public List<stats> viewerstats { get; set; }
    public String version { get; set; }

    public ViewerStatsFormat(bool chk)
    {
        this.viewerstats = new List<stats>();
    }
}

이 클래스의 한 개체는 다음으로 채워지고 저장됩니다.

 File.WriteAllText(tmpfile, JsonConvert.SerializeObject(current), Encoding.UTF8);

저장 부분이 제대로 작동하고 파일이 존재하고 채워집니다. 그 후 파일은 다음과 같이 클래스로 다시 읽 힙니다.

    try 
{ 

    ViewerStatsFormat current = JsonConvert.DeserializeObject<ViewerStatsFormat>(tmpfile);
    //otherstuff        

}
catch(Exception ex)
{
    //error loging stuff
}

이제 current = 줄에 예외가 있습니다.

{ "값을 구문 분석하는 동안 예기치 않은 문자가 발견되었습니다. e. 경로 '', 줄 0, 위치 0."}

나는 이것이 왜 오는지 모른다. json 파일은 다음과 같습니다-> JSON 링크에서 나를 클릭하십시오.

누구에게 아이디어가 있습니까?


아마도 JSON을 DeserializeObject.

그것은에서 모양 File.WriteAllText(tmpfile,...의 유형 tmpfileIS string파일의 경로가 포함되어 있습니다. JsonConvert.DeserializeObject파일 경로가 아닌 JSON 값을 사용하므로 @"c:\temp\fooo"JSON이 아닌 것과 같은 변환을 시도 하지 못합니다.


다음 온라인 도구로 문제를 해결했습니다.

  1. Json 구조가 OKAY인지 확인하려면 : http://jsonlint.com/
  2. 내 Json 구조에서 내 Object 클래스를 생성하려면 : http://json2csharp.com/

간단한 코드 :

RootObject rootObj= JsonConvert.DeserializeObject<RootObject>(File.ReadAllText(pathFile));

내 Xamarin.Android 솔루션에서 동일한 오류가 발생했습니다.

내 JSON이 올바른지 확인했고 앱을 릴리스 빌드로 실행할 때만 오류가 나타나는 것을 확인했습니다.

링커가 Newtonsoft.JSON에서 라이브러리를 제거하여 JSON이 잘못 구문 분석되는 것으로 밝혀졌습니다.

Android 빌드 구성의 어셈블리 무시 설정에 Newtonsoft.Json을 추가하여 오류를 수정했습니다 (아래 스크린 샷).

JSON 구문 분석 코드

static readonly JsonSerializer _serializer = new JsonSerializer();
static readonly HttpClient _client = new HttpClient();

static async Task<T> GetDataObjectFromAPI<T>(string apiUrl)
{
    using (var stream = await _client.GetStreamAsync(apiUrl).ConfigureAwait(false))
    using (var reader = new StreamReader(stream))
    using (var json = new JsonTextReader(reader))
    {
        if (json == null)
            return default(T);

        return _serializer.Deserialize<T>(json);
    }
}

Visual Studio Mac 스크린 샷

enter image description here

Visual Studio 스크린 샷

enter image description here


이 문제는 JSON 파일의 바이트 순서 표시와 관련이 있습니다. JSON 파일은 저장할 때 UTF8 인코딩 데이터로 인코딩되지 않습니다. File.ReadAllText(pathFile)이 문제 수정하십시오.

Byte 데이터에 대해 작업하고이를 문자열로 변환 한 다음 JsonConvert.DeserializeObject에 전달할 때 UTF32 인코딩을 사용하여 문자열을 가져올 수 있습니다.

byte[] docBytes = File.ReadAllBytes(filePath);

string jsonString = Encoding.UTF32.GetString(docBytes);


이것이 당신의 json이라고 가정하십시오.

{
  "date":"11/05/2016",
  "venue": "{\"ID\":12,\"CITY\":Delhi}"
}

다시 deserialize 장소를 원한다면 아래와 같이 json을 수정하십시오.

{
  "date":"11/05/2016",
  "venue": "{\"ID\":\"12\",\"CITY\":\"Delhi\"}"
}

그런 다음 장소의 가치를 취하여 각 클래스로 역 직렬화를 시도하십시오.


I had the same problem with webapi in ASP.NET core, in my case it was because my application needs authentication, then it assigns the annotation [AllowAnonymous] and it worked.

[AllowAnonymous]
public async Task <IList <IServic >> GetServices () {
        
}

If you are using downloading data using url...may need to use

var result = client.DownloadData(url);


Please check the model you shared between client and server is same. sometimes you get this error when you not updated the Api version and it returns a updated model, but you still have an old one. Sometimes you get what you serialize/deserialize is not a valid JSON.


In my scenario I had a slightly different message, where the line and position were not zero.

E. Path 'job[0].name', line 1, position 12.

This was the top Google answer for the message I quoted.

This came about because I had called a program from the Windows command line, passing JSON as a parameter.

When I reviewed the args in my program, all the double quotes got stripped. You have to reconstitute them.

I posted a solution here. Though it could probably be enhanced with a Regex.


I had a similar error and thought I'd answer in case anyone was having something similar. I was looping over a directory of json files and deserializing them but was getting this same error.

The problem was that it was trying to grab hidden files as well. Make sure the file you're passing in is a .json file. I'm guessing it'll handle text as well. Hope this helps.


I faced similar error message in Xamarin forms when sending request to webApi to get a Token,

  • Make sure all keys (key : value) (ex.'username', 'password', 'grant_type') in the Json file are exactly what the webApi expecting, otherwise it fires this exception.

Unhandled Exception: Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: <. Path '', line 0, position 0


When I encountered a similar problem, I fixed it by substituting &mode=xml for &mode=json in the request.

참고URL : https://stackoverflow.com/questions/23259173/unexpected-character-encountered-while-parsing-value

반응형