Home > Back-end >  How to pass none english letters to Json
How to pass none english letters to Json

Time:11-04

I'm working on a Xamarin Forms app for Android & iOS

I'm trying to figure out how to pass none english letters to Json file.

My language is Swedish and whenever I use characters like (Å, Ä, Ö) the app crashes.

So how do I fix this please ?

DrawerViewModel.cs

class DrawerViewModel : BaseViewModel {
     ...

     public static DrawerViewModel BindingContext => 
        drawerViewModel = PopulateData<DrawerViewModel>("drawer.json");

     ...

     private static T PopulateData<T>(string fileName)
    {
        var file = "CykelStaden.Data."   fileName;

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

        T data;

        using (var stream = assembly.GetManifestResourceStream(file))
        {
            var serializer = new DataContractJsonSerializer(typeof(T));
            data = (T)serializer.ReadObject(stream);
        }

        return data;
    }
     
}

drawer.json

{
    "itemList": [
     {
         "itemIcon": "\ue729",
         "itemName": "Länd"
      },
      {
          "itemIcon": "\ue72c",
          "itemName": "Höjd"
      },
      {
          "itemIcon": "\ue733",
          "itemName": "Mått"
      },
      {
          "itemIcon": "\ue72b",
          "itemName": "Inställningar"
      }
  ]
}

CodePudding user response:

The json parser crashes, because the json data is not encoded correctly. The special caracters (ä, ö, å) have to be encoded with the same \u syntax.

Using this should work:

{
  "itemList": [
    {
      "itemIcon": "\uE729",
      "itemName": "L\u00E4nd"
    },
    {
      "itemIcon": "\uE72C",
      "itemName": "H\u00F6jd"
    },
    {
      "itemIcon": "\uE733",
      "itemName": "M\u00E5tt"
    },
    {
      "itemIcon": "\uE72B",
      "itemName": "Inst\u00E4llningar"
    }
  ]
}

CodePudding user response:

Out of curiosity I found another Solution: https://docs.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-character-encoding

Using the included JsonSerializer:

using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Unicode;

public class Data
{
    public class Item
    {
        public string itemIcon { get; set; }
        public string itemName { get; set; }
    }

    public IEnumerable<Item> itemList { get; set; }
}


static class Program
{
    static void Main()
    {
        string json = File.ReadAllText("data.json");

        JsonSerializerOptions serializerOptions = new JsonSerializerOptions
        {
            Encoder = JavaScriptEncoder.Create(UnicodeRanges.All)
        };

        var data = JsonSerializer.Deserialize<Data>(json, serializerOptions);

        foreach (var item in data.itemList) 
        {
            Console.WriteLine($"{item.itemIcon}; {item.itemName}");
        }
    }
}
  • Related