0

When I try to deserialize a JSON file with a 'Ñ' I get the exception:

'Exception has been thrown by the target of an invocation. ---> System.Xml.XmlException: '� 1' contains invalid UTF8 bytes. ---> System.Text.DecoderFallbackException: Unable to translate bytes [F1] at index 0 from specified code page to Unicode.'

This is the json object:

{
  "id": "1",
  "previewimages": [
    { "previewimage": "RutaÑaguarma1.png" },
    { "previewimage": "RutaÑaguarma2.png" },
    { "previewimage": "RutaÑaguarma3.png" },
    { "previewimage": "RutaÑaguarma4.png" },
    { "previewimage": "RutaÑaguarma5.png" }
  ],
  "previewimage": "RutaÑaguarma.png",
  "name": "Ruta Ñaguarma",
  "description": "Sendero realizado desde el pueblo, por un camino paralelo a la playa, pero por un bosque húmedo interior. La vuelta la realizamos por la arena de la playa.",
  "distance": "5,89 km",
  "averageDuration": "60 min",
  "difficultyLevel": "3",
  "overallrating": "4.7",
  "subcategoryid": "6"
},

This is the method:

    /// <summary>
    /// Populates the data from json file.
    /// </summary>
    /// <param name="fileName">Json file to fetch data.</param>
    private static T PopulateData<T>(string fileName)
    {
        string file = "TortuguiaApp.MockData." + fileName;

        Assembly assembly = typeof(App).GetTypeInfo().Assembly;

        T obj;

        using (System.IO.Stream stream = assembly.GetManifestResourceStream(file))
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            obj = (T)serializer.ReadObject(stream);
        }

        return obj;
    }

¿How can I use DataContractJsonSerializer alowing Ñ and words with accents?

Maritim
  • 2,111
  • 4
  • 29
  • 59
Daniel
  • 1
  • 2
  • Check to see whether your manifest resource stream starts with a BOM. If so, remove it. See [Why does text from Assembly.GetManifestResourceStream() start with three junk characters?](https://stackoverflow.com/q/578752/3744182). – dbc Apr 29 '22 at 21:49

1 Answers1

0

Just use Newtonsoft.Json.

 string file = @"TortuguiaApp.MockData." + fileName;
 var json =File.ReadAllText(file);

var jsonParsed = JObject.Parse(json);

//or 

var obj = JsonConvert.DeserializeObject<T>(json);
Serge
  • 40,935
  • 4
  • 18
  • 45
  • Or [System.Text.Json](https://learn.microsoft.com/en-us/dotnet/api/system.text.json?view=net-6.0) – ThomasArdal Apr 30 '22 at 08:06
  • @ThomasArdal No , system.text.json is not so good. it will replace with \u00D1 . You will need some extra code to make it work properly – Serge Apr 30 '22 at 10:48