简体   繁体   English

JSON 添加节点到现有的 JObject

[英]JSON add node to an existing JObject

I am trying to add a new node to an existing JSON JObject , but when I add it does not format correctly.我正在尝试向现有的JSON JObject添加一个新节点,但是当我添加它时,它的格式不正确。 It adds quotes around the entire node, and \\ are put in place.它在整个节点周围添加引号,并将 \\ 放在适当的位置。

Background: I am loading a JSON file, doing some logic then adding a node back in. Figured I can do it like this:背景:我正在加载一个JSON文件,执行一些逻辑,然后重新添加一个节点。我想我可以这样做:

mainJson.Add("NewNode", JsonConvert.SerializeObject(MyObject));
File.WriteAllText("myfile.json", mainJson.ToString());

Problem is that this is the result:问题是结果如下:

{
"JSONFile": [
  {
    "More": "Nodes",
    "InThe": "File"
  }
],
"Customers": "{\"FirstName\":\"Mike\",\"LastName\":\"Smith\"},{\"FirstName\":\"Jane\",\"LastName\":\"Doe\"}",
}

I know that my JsonConvert.SerializeObject(MyObject) is working if I do this:如果我这样做,我知道我的 JsonConvert.SerializeObject(MyObject) 正在工作:

string json = JsonConvert.SerializeObject(MyObject);
File.WriteAllText("myfile2.json" json);

The result is this:结果是这样的:

[
  {
    "FirstName": "Mike",
    "LastName": "Smith"
  },
  {
    "FirstName": "Jane",
    "LastName": "Doe"
  }
]

What am I missing?我错过了什么?

edit: Following @Swagata Prateek comment of;编辑:以下@Swagata Prateek 评论;

mainJson.Add("Customers",JObject.FromObject(MyObject));

An unhandled exception of type 'System.ArgumentException' occurred in Newtonsoft.Json.dll Newtonsoft.Json.dll 中发生类型为“System.ArgumentException”的未处理异常

Additional information: Object serialized to Array.附加信息:对象序列化为数组。 JObject instance expected.预期的 JObject 实例。

I should note that MyObject is actual ObservableCollection if that makes a difference我应该注意到 MyObject 是实际的ObservableCollection如果这有所不同

Could you kindly try with this?你可以试试这个吗?

mainJson.Add("NewNode", JObject.FromObject(MyObject));
File.WriteAllText("myfile.json", mainJson.ToString());

When you are doing JsonConvert.SerializeObject(MyObject) it serializes MyObject and in the process you get a string out of it.当您执行JsonConvert.SerializeObject(MyObject)它会序列化MyObject并在此过程中您从中得到一个字符串。

When you assign mainJson.Add("NewNode", JsonConvert.SerializeObject(MyObject));当您分配mainJson.Add("NewNode", JsonConvert.SerializeObject(MyObject)); you're assigning a string to NewNode .您正在为NewNode分配一个字符串。 Thus you get a quoted string that represents serialized MyObject因此,您将获得一个表示序列化MyObject带引号的字符串

Update :更新

JArray.FromObject is the method you'd want to look for if you want to convert your collection to a JArray.如果要将集合转换为JArray.FromObject是您想要查找的方法。 In that case the segment would look something like在这种情况下,该段看起来像

mainJson.Add("NewNode", JArray.FromObject(obsColl));
File.WriteAllText("myfile.json", mainJson.ToString());
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            JObject tempvar= JObject.Parse(@"{
  'CPU': 'Intel',
  'Drives': [
    'DVD read/writer',
    '500 gigabyte hard drive'
  ]
}");
            string cpu = (string)tempvar["CPU"];          // Intel
            string firstDrive = (string)tempvar["Drives"][0];   // DVD read/writer
IList<string> allDrives = tempvar["Drives"].Select(t => (string)t).ToList();
            // DVD read/writer
            // 500 gigabyte hard drive

            tempvar["Drives"][0].AddAfterSelf("new node");
//tempvar json with new node
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM