【发布时间】:2021-09-05 04:44:10
【问题描述】:
嘿,我想弄清楚如何在我的 JSON 类中只保存一个值,而不必用“New”再次写出整个 JSON。我正在使用 Newton JSON.Net。
这是我的 JSON 结构:
public class GV
{
public class Data
{
[JsonProperty("pathForNESPosters")]
public static string PathForNESPosters { get; set; }
[JsonProperty("pathForSNESPosters")]
public static string PathForSNESPosters { get; set; }
[JsonProperty("pathForSEGAPosters")]
public static string PathForSEGAPosters { get; set; }
[JsonProperty("pathToNESContent")]
public static string PathToNESContent { get; set; }
[JsonProperty("pathToSNESContent")]
public static string PathToSNESContent { get; set; }
[JsonProperty("pathToSEGAContent")]
public static string PathToSEGAContent { get; set; }
[JsonProperty("lastSavedVolume")]
public static double LastSavedVolume { get; set; }
}
public class Root
{
public Data data { get; set; }
}
而且我将文件中的数据加载到我的类中没有问题:
GV.Root myDeserializedClass = JsonConvert.DeserializeObject<GV.Root>(File.ReadAllText(
currentAssemblyPath + String.Format(@"\Resources\{0}", "dataForLinks.json")
));
但是我还没有找到任何搜索可以让我对类中的对象进行一次更新,而不会通过 New 语句将其清除。
我想要做的事情如下:
-Load the json into my class object [Done]
-Save a value thats in my class object [stuck here]
GV.pathToNESContent = "new value here";
-Save class object (with the one new value) back to the file for which it came from preserving the other original values. [not here yet]
当我只更新一个类对象时,我希望包含我从文件中读取的所有其他 JSON 数据的原始值。
谁有上述的好例子可以分享?
更新
【问题讨论】:
-
不就是
GV.Root.pathToNESContent = "new value here";吗? -
@Felix 从技术上讲它是
PathToNES.. 带有大写的P,并且实例不称为GV.Root,但我知道你的意思! ;) -
@StealthRT
GV.pathToNESContent = "new value here";- 但是,GV 类不包含属性调用pathToNESContent并且您希望有一个名为myDeserializedClasss的实例,因此使用该类型的静态访问方法名称不合适...我想我会将 GV 转换为名称空间,tbh(与您的问题无关,只是您似乎不需要内部类,它们实际上似乎引起了混乱)跨度> -
@CaiusJard - 当然!只是感觉还有更多的问题......
-
@Felix 是的,我认为它也会以这种方式工作,但它似乎不想这样做。请参阅更新的 OP。
标签: c# json class object json.net