Daniel
Daniel

Reputation: 1

DataContractJsonSerializer contains invalid UFT8 bytes

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?

Upvotes: 0

Views: 227

Answers (1)

Serge
Serge

Reputation: 43850

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);

Upvotes: 0

Related Questions