2

There is a class, Data. Data has a member, "name" which contains Korean string.

I make json string with System.Text.Json

JsonSerializer.Serialize<Data>(data, opt);

and make json file

File.WriteAllText(filePath, jsonstring, Encoding.UTF8);

part of json is

"name": "\uC0BC\uC131\uC804\uAE30",

but Json string what I want is

"name": "삼성전기",

I tried

File.WriteAllText(filePath, jsonstring, Encoding.Unicode)
File.WriteAllText(filePath, jsonstring, Encoding.Default)

but the contents of the file are in this format \uxxxx.

How can I save Korean string to file as it is?

(As a reference) When I try to find solution (for C#) I found out function(json.dumps) in Python I can get the results what I want by using it

(example)

import json
dict = {'555': '123'}
with open('file.txt', 'w', encoding='UTF-8') as file:
file.write(json.dumps(dict))
2
  • 3
    What is the value in jsonstring ? If jsonstring contains "name": "\uC0BC\uC131\uC804\uAE30", then that is what the string contains, and what it will always contain. How you encode that doesn't matter; the real question then moves back a step: how to get JsonSerializer to not escape those values. Can you show the code that produces jsonstring? Note: this probably comes down to setting opt.Encoder = ... (to something) Commented Jan 26, 2021 at 15:29
  • 1
    Looks like a duplicate of dotnet core System.Text.Json unescape unicode string, agree? Commented Jan 26, 2021 at 17:13

1 Answer 1

2

What you probably want here is - right at the start:

opt.Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping;

(obviously don't change this constantly - set it once only; if a different usage needs different options: use a different options object)

This leaves the Name unescaped, rather than escaping it in the JSON. From there, you can then encode the string any way you like.

You should also note that the name UnsafeRelaxedJsonEscaping suggests that there may be scenarios in which this is undesirable, so: it would be worth trying to read the documentation on UnsafeRelaxedJsonEscaping to understand when and why this is.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.