반응형
JSON 파일의 값 변경(파일 쓰기)
어플리케이션의 Release 폴더에 settings.json 파일이 있습니다.내가 하고 싶은 것은 일시적으로가 아니라 영구적으로 그것의 가치를 바꾸는 것이다.즉, 이전 엔트리를 삭제하고 새 엔트리를 작성하여 저장합니다.
다음은 JSON 파일의 형식입니다.
{
"Admins":["234567"],
"ApiKey":"Text",
"mainLog": "syslog.log",
"UseSeparateProcesses": "false",
"AutoStartAllBots": "true",
"Bots": [
{
"Username":"BOT USERNAME",
"Password":"BOT PASSWORD",
"DisplayName":"TestBot",
"Backpack":"",
"ChatResponse":"Hi there bro",
"logFile": "TestBot.log",
"BotControlClass": "Text",
"MaximumTradeTime":180,
"MaximumActionGap":30,
"DisplayNamePrefix":"[AutomatedBot] ",
"TradePollingInterval":800,
"LogLevel":"Success",
"AutoStart": "true"
}
]
}
패스워드 값을 변경하고 BOT PASSWORD 대신 패스워드만 변경한다고 가정합니다.그걸 어떻게 하는 거죠?
여기 그것을 하는 간단하고 저렴한 방법이 있습니다(가정).NET 4.0 이후):
string json = File.ReadAllText("settings.json");
dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
jsonObj["Bots"][0]["Password"] = "new password";
string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText("settings.json", output);
의 사용dynamic
를 사용하면 json 개체 및 어레이에 매우 간단하게 인덱싱할 수 있습니다.다만, 컴파일 타임 체크에서는 확실히 손해를 보게 됩니다.퀵 앤 더티에는 정말 좋지만 프로덕션 코드에는 @gitesh.tyagi의 솔루션과 같은 풀 살코기 클래스가 필요할 것입니다.
를 사용합니다.JObject
을 수업하다.Newtonsoft.Json.Linq
사전에 JSON 구조를 파악하지 않고 JSON 값을 변경하려면 다음 절차를 수행합니다.
using Newtonsoft.Json.Linq;
string jsonString = File.ReadAllText("myfile.json");
// Convert the JSON string to a JObject:
JObject jObject = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString) as JObject;
// Select a nested property using a single string:
JToken jToken = jObject.SelectToken("Bots[0].Password");
// Update the value of the property:
jToken.Replace("myNewPassword123");
// Convert the JObject back to a string:
string updatedJsonString = jObject.ToString();
File.WriteAllText("myfile.json", updatedJsonString);
예:
// This is the JSON string from the question
string jsonString = "{\"Admins\":[\"234567\"],\"ApiKey\":\"Text\",\"mainLog\":\"syslog.log\",\"UseSeparateProcesses\":\"false\",\"AutoStartAllBots\":\"true\",\"Bots\":[{\"Username\":\"BOT USERNAME\",\"Password\":\"BOT PASSWORD\",\"DisplayName\":\"TestBot\",\"Backpack\":\"\",\"ChatResponse\":\"Hi there bro\",\"logFile\":\"TestBot.log\",\"BotControlClass\":\"Text\",\"MaximumTradeTime\":180,\"MaximumActionGap\":30,\"DisplayNamePrefix\":\"[AutomatedBot] \",\"TradePollingInterval\":800,\"LogLevel\":\"Success\",\"AutoStart\":\"true\"}]}";
JObject jObject = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString) as JObject;
// Update a string value:
JToken jToken = jObject.SelectToken("Bots[0].Password");
jToken.Replace("myNewPassword123");
// Update an integer value:
JToken jToken2 = jObject.SelectToken("Bots[0].TradePollingInterval");
jToken2.Replace(555);
// Update a boolean value:
JToken jToken3 = jObject.SelectToken("Bots[0].AutoStart");
jToken3.Replace(false);
// Get an indented/formatted string:
string updatedJsonString = jObject.ToString();
//Output:
//{
// "Admins": [
// "234567"
// ],
// "ApiKey": "Text",
// "mainLog": "syslog.log",
// "UseSeparateProcesses": "false",
// "AutoStartAllBots": "true",
// "Bots": [
// {
// "Username": "BOT USERNAME",
// "Password": "password",
// "DisplayName": "TestBot",
// "Backpack": "",
// "ChatResponse": "Hi there bro",
// "logFile": "TestBot.log",
// "BotControlClass": "Text",
// "MaximumTradeTime": 180,
// "MaximumActionGap": 30,
// "DisplayNamePrefix": "[AutomatedBot] ",
// "TradePollingInterval": 555,
// "LogLevel": "Success",
// "AutoStart": false
// }
// ]
//}
json 값을 다음과 같이 인스턴스화하는 클래스가 있어야 합니다.
public class Bot
{
public string Username { get; set; }
public string Password { get; set; }
public string DisplayName { get; set; }
public string Backpack { get; set; }
public string ChatResponse { get; set; }
public string logFile { get; set; }
public string BotControlClass { get; set; }
public int MaximumTradeTime { get; set; }
public int MaximumActionGap { get; set; }
public string DisplayNamePrefix { get; set; }
public int TradePollingInterval { get; set; }
public string LogLevel { get; set; }
public string AutoStart { get; set; }
}
public class RootObject
{
public List<string> Admins { get; set; }
public string ApiKey { get; set; }
public string mainLog { get; set; }
public string UseSeparateProcesses { get; set; }
public string AutoStartAllBots { get; set; }
public List<Bot> Bots { get; set; }
}
Ques(테스트되지 않은 코드)에 대한 답변:
//Read file to string
string json = File.ReadAllText("PATH TO settings.json");
//Deserialize from file to object:
var rootObject = new RootObject();
JsonConvert.PopulateObject(json, rootObject);
//Change Value
rootObject.Bots[0].Password = "password";
// serialize JSON directly to a file again
using (StreamWriter file = File.CreateText(@"PATH TO settings.json"))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, rootObject);
}
언급URL : https://stackoverflow.com/questions/21695185/change-values-in-json-file-writing-files
반응형
'programing' 카테고리의 다른 글
Wordpress 게시물/페이지에 위젯을 단축코드로 추가하는 방법은 무엇입니까? (0) | 2023.03.18 |
---|---|
Jenkins 오류 - 문서 프레임이 샌드박스에 저장되고 '스크립트 허용' 권한이 설정되지 않아 에서 스크립트 실행이 차단되었습니다. (0) | 2023.03.18 |
Wordpress 제목: 50자를 초과하는 경우 생략 부호 표시 (0) | 2023.03.18 |
React에서 상태 비저장 구성 요소의 참조에 연결하는 방법은 무엇입니까? (0) | 2023.03.18 |
Spring REST 서비스: json 응답의 null 개체를 제거하도록 구성하는 방법 (0) | 2023.03.18 |