英文:
Make the JSON string to be tree based after deserialization without the class
问题
Here is the translated JSON string:
{"fields":{"CurrentPage":14,"CurrentSubPageNo":18,"IsFileUpload":false,"VisitedPages":[2,3,4,6,7,8,10,11,12,13,14]}}
If you have any more translation needs, please let me know.
英文:
I have the following JSON string
{"fields": "{\n \"CurrentPage\": 14,\n \"CurrentSubPageNo\": 18,\n \"IsFileUpload\": false,\n \"VisitedPages\": [\n 2,\n 3,\n 4,\n 6,\n 7,\n 8,\n 10,\n 11,\n 12,\n 13,\n 14\n ]\n}"}
How can I make it to be like the following in C#?
{"fields":{"CurrentPage":14,"CurrentSubPageNo":18,"IsFileUpload":false,"VisitedPages":[2,3,4,6,7,8,10,11,12,13,14]}}
I am using Newtonsoft.Json
and I do not know on how to achieve like the above result
Please do take a note that the value inside fields
can be dynamic (which the key and value inside it can be present or not), which is why deserialize to a class for the value inside fields
is not an option for me
Anyone knows on how to do it?
Thank you very much
答案1
得分: 2
这是相对简单的操作:
- 反序列化为
JObject
- 获取
fields
的值,该值应该是一个字符串 - 将其解析为
JObject
- 将
fields
的值设置为解析后的值 - 将
JObject
重新序列化为字符串
示例代码 - 当然,缺少错误处理:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
string originalJson = File.ReadAllText("test.json");
Console.WriteLine($"Original JSON: {originalJson}");
JObject obj = JObject.Parse(originalJson);
string fieldsJson = (string) obj["fields"];
JObject fieldsObj = JObject.Parse(fieldsJson);
obj["fields"] = fieldsObj;
string newJson = obj.ToString(Formatting.None);
Console.WriteLine($"New JSON: {newJson}");
英文:
This is reasonably simple:
- Deserialize to a
JObject
- Fetch the value of
fields
, which should be a string - Parse that as a
JObject
- Set the value of
fields
to the parsed value - Reserialize the
JObject
to a string
Sample code - lacking error handling, of course:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
string originalJson = File.ReadAllText("test.json");
Console.WriteLine($"Original JSON: {originalJson}");
JObject obj = JObject.Parse(originalJson);
string fieldsJson = (string) obj["fields"];
JObject fieldsObj = JObject.Parse(fieldsJson);
obj["fields"] = fieldsObj;
string newJson = obj.ToString(Formatting.None);
Console.WriteLine($"New JSON: {newJson}");
答案2
得分: 1
"fields"属性的JSON对象被序列化两次,因此您只需解析两次。您可以将所有代码放在一行中:
json = new JObject { ["fields"] = JObject.Parse(
(string) JObject.Parse(json)["fields"])}.ToString(Newtonsoft.Json.Formatting.None);
英文:
your "fields" property of json object is serialized twice, so you need just parse it twice. You can put all code in one line
json = new JObject { ["fields"] = JObject.Parse(
(string) JObject.Parse(json)["fields"])}.ToString(Newtonsoft.Json.Formatting.None);
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论