鉴于结构:
public class ProjectKey
{
public string Key;
public bool Parent;
}
List<ProjectKey>
按字母顺序给出,其中包含以下值:
Key Parent
--------------------------
text 1
text.ui 1
text.ui.hello 0
text.ui.goodbye 0
text.ui.popup 0
text.ui.project 1
text.ui.project.val 0
text.ui.project.val2 0
如何使用空值轻松将其转换为JSON格式?例如,上面的列表将给出输出:
{
"text": {
"ui": {
"hello": "",
"goodbye": "",
"popup": "",
"project":{
"val": "",
"val2": ""
}
}
}
}
JSON.net是否可以通过这种方式为我进行序列化?或者我需要编写自己的转换器吗?
答案 0 :(得分:1)
JObject
似乎特别适合这样的事情:
public string SerializeProjectKeys(List<ProjectKey> pks)
{
JObject toSerialize = new JObject();
foreach (ProjectKey pk in pks)
{
string[] keyParts = pk.Key.Split('.');
JObject currentObj = toSerialize;
for (int i = 0; i < keyParts.Length; i++)
{
string keyPart = keyParts[i];
if (i == keyParts.Length - 1)
{
if (pk.Parent)
{
currentObj.Add(keyPart, new JObject());
}
else
{
currentObj.Add(keyPart, string.Empty);
}
}
else
{
currentObj = (JObject)currentObj[keyPart];
}
}
}
return toSerialize.ToString();
}
答案 1 :(得分:-1)
我知道对字符串的JSON操作不太好。但我从未使用C#创建JSON对象。可能你的问题并不包含所有数据,但我认为这可能对主要想法有所帮助:
List<ProjectKey> projectKeys = new List<ProjectKey>();
projectKeys.Add(new ProjectKey("text", true));
projectKeys.Add(new ProjectKey("text.ui", true));
projectKeys.Add(new ProjectKey("text.ui.hello", false));
projectKeys.Add(new ProjectKey("text.ui.goodbye", false));
projectKeys.Add(new ProjectKey("text.ui.popup", false));
projectKeys.Add(new ProjectKey("text.ui.project", true));
projectKeys.Add(new ProjectKey("text.ui.project.val", false));
projectKeys.Add(new ProjectKey("text.ui.project.val2", false));
StringBuilder output = new StringBuilder();
for (int i = 0; i < projectKeys.Count; i++)
{
if (projectKeys[i].Parent)
{
// If current key is parent - do not close bracket.
output.AppendLine(string.Format("\"{0}\": {{", projectKeys[i].Key.Split('.').Last()));
}
else
{
// If this is no ones parent - close bracket.
output.AppendLine(string.Format("\"{0}\": \"\"", projectKeys[i].Key.Split('.').Last()));
}
}
// Append as many closing brackets as there are many parents.
for (int i = 0; i < projectKeys.Where(x => x.Parent).Count(); i++)
{
output.AppendLine("}");
}
Console.Write(output.ToString());
恕我直言,这是一种奇怪的树,包含“我是父母”的信息 - 我建议包含“我父母”的财产。