简体   繁体   English

如何在不使用 JSON.Net 库创建自定义类的情况下从字符串创建 JSON

[英]How to create JSON from strings without creating a custom class using JSON.Net library

I have this method in which I'm trying to create JSON string:我有这个方法,我正在尝试创建 JSON 字符串:

//my current file
using Newtonsoft.Json;
string key1 = "FirstKey";
string key2 = "SecondKey";
string key3 = "ThirdKey";
private string CreateJson(string val1,  string val2, string val3,string val4,  string val5, string val6)
{
    //process the six arguments and three key-related member variables to create a JSON array
    //don't want to use JsonConvert.SerializeObject the way I'm doing below as it requires creating a class

    var configs = new List<CustomClass>
                         { new CustomClass{ FirstKey = val1,SecondKey= val2,ThirdKey= val3}
                            , new CustomClass{ FirstKey= val4,SecondKey= val5,ThirdKey = val6}
                        };
    var jsonData = JsonConvert.SerializeObject(configs);
   return jsonData;
}

//A class in another file
public class CustomClass
{
    public string FirstKey { get; set; }
    public string SecondKey{ get; set; }
    public string ThirdKey{ get; set; }

}

I'm trying to create the JSON array using JSON.Net.我正在尝试使用 JSON.Net 创建 JSON 数组。 The expected output is as below:预期输出如下:

[{"FirstKey":val1,"SecondKey":val2,"ThirdKey":val3}
, {"FirstKey":val4,"SecondKey":val5,"ThirdKey":val6}]

Here val1 to val6 values should get replaced by the argument values at run-time.这里val1val6的值应该在运行时被参数值替换。

Initially, since there were just three types of string key-value pairs, so I thought it would be pretty straightforward to create a JSON string simply by using string literals and appending then one after the other in JSON format.最初,由于只有三种类型的字符串键值对,所以我认为通过使用字符串文字并以 JSON 格式一个接一个地附加来创建 JSON 字符串会非常简单。 But soon I stumbled upon the world of escape characters which can deform a JSON string eg \r .但很快我偶然发现了转义字符的世界,它可以使 JSON 字符串变形,例如\r

I had been using JSON.Net library in the past simply to serialize and deserialize objects using JSONConvert class and I never cared and was completely unaware about this handling of escape characters by JSON.Net library does behind the scene for us to keep the JSON string valid.我过去一直在使用 JSON.Net 库,只是为了使用JSONConvert类序列化和反序列化对象,而我从不关心并且完全不知道 JSON.Net 库在幕后为我们保留 JSON 字符串所做的转义字符处理有效的。

Anyways, coming back to my problem.无论如何,回到我的问题。 I was able to solve my problem by creating a custom class having three properties FirstKey , SecondKey , and ThirdKey .我能够通过创建具有三个属性FirstKeySecondKeyThirdKey的自定义类来解决我的问题。 Then, create an object of the class, then assign the values in arguments val1 and val2 to then and then use JsonConvert.SerializeObject API.然后,创建该类的一个对象,然后将参数val1val2中的值分配给 then,然后使用JsonConvert.SerializeObject API。

I want a very simply way of creating JSON string using JSON.Net NuGet package without involving custom classes.我想要一种非常简单的方法来使用 JSON.Net NuGet 包创建 JSON 字符串,而不涉及自定义类。 Creating a class CustomClass altogether feels like an overhead here.在这里完全创建一个类CustomClass感觉像是一种开销。 I'm looking for something of sort of like StringBuilder.Append API if it is available in the JSON library I'm using.我正在寻找类似于StringBuilder.Append API 的东西,如果它在我正在使用的 JSON 库中可用。 I'm not sure if I'm missing any of the APIs in JSON.Net.我不确定我是否缺少 JSON.Net 中的任何 API。

As mentioned in the comments, you could just as easily have created it using anonymous objects.正如评论中提到的,您可以使用匿名对象轻松创建它。

private string CreateJson(string val1, string val2, string val3, string val4, string val5, string val6) {

    var configs = new[]
    { 
        new { FirstKey = val1, SecondKey = val2, ThirdKey = val3}, 
        new { FirstKey = val4, SecondKey = val5, ThirdKey = val6}
    };

    var jsonData = JsonConvert.SerializeObject(configs);

    return jsonData;
}

Getting few clues from [@code4life][1]'s comment in accepted answer, I found out that it is achievable via JArray object as well found under Newtonsoft.Json.Linq namespace.从 [@code4life][1] 在接受的答案中的评论中得到一些线索,我发现它可以通过JArray对象实现,也可以在Newtonsoft.Json.Linq命名空间下找到。

using Newtonsoft.Json.Linq;

private string CreateJson(string val1, string val2, string val3, string val4, string val5, string val6) 
{

    var configs = new[]
    { 
        new { FirstKey = val1, SecondKey = val2, ThirdKey = val3}, 
        new { FirstKey = val4, SecondKey = val5, ThirdKey = val6}
    };

    return JArray.FromObject(configs).ToString();
}

Note : Anonymous types which are being created through new { FirstKey = val1, SecondKey = val2, ThirdKey = val3} syntax can contain any .NET data type and not just strings which I've asked in my original post eg new { FirstKey = "AnyString", SecondKey = true, ThirdKey = DateTime.Now} [1]: https://stackoverflow.com/users/215741/code4life注意:通过new { FirstKey = val1, SecondKey = val2, ThirdKey = val3}语法创建的匿名类型可以包含任何 .NET 数据类型,而不仅仅是我在原始帖子中询问的字符串,例如new { FirstKey = "AnyString", SecondKey = true, ThirdKey = DateTime.Now} [1]: https ://stackoverflow.com/users/215741/code4life

Here's an alternate way of doing it.这是另一种方法。 My use case is I need to read a CSV file, and create JSON output based on the CSV headers.我的用例是我需要读取 CSV 文件,并根据 CSV 标头创建 JSON 输出。 I do not know what the key names will be.我不知道key名是什么。 Every CSV file could have different headers.每个 CSV 文件都可以有不同的标题。

Rick Strahl shows us how to do it @ https://weblog.west-wind.com/posts/2012/aug/30/using-jsonnet-for-dynamic-json-parsing Rick Strahl 向我们展示了如何做到这一点 @ https://weblog.west-wind.com/posts/2012/aug/30/using-jsonnet-for-dynamic-json-parsing

And here's a simple implementation using JObject and JArray这是一个使用 JObject 和 JArray 的简单实现

Create a dotnet new console project and add the nuget package for Newtonsoft创建 dotnet new 控制台项目并添加 Newtonsoft 的 nuget 包

dotnet new console -n "Json.TypeLess"
dotnet add package Newtonsoft.Json --version 13.0.1

Program.cs to have : Program.cs 有:

using Newtonsoft.Json.Linq;

namespace Json.TypeLess
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var records = new JArray();
            records.Add(CreateRecord("Johhny", "Singing"));
            records.Add(CreateRecord("Arjun", "Eating"));
            records.Add(CreateRecord("Sahil", "Reading"));
            records.Add(CreateRecord("Karthik", "Wuxia"));

            Console.WriteLine(records.ToString());
        }

        static JObject CreateRecord(string name, string likes)
        {
            var r = new JObject();
            r.Add("Name", name);
            r.Add("Likes", likes);
            return r;
        }
    }

}

Output输出

[
  {
    "Name": "Johhny",
    "Likes": "Singing"
  },
  {
    "Name": "Arjun",
    "Likes": "Eating"
  },
  {
    "Name": "Sahil",
    "Likes": "Reading"
  },
  {
    "Name": "Karthik",
    "Likes": "Wuxia"
  }
]

Without using NewtonSoft Json不使用 NewtonSoft Json

The above can also be achieved using System.Text.Json.Nodes namespace from .net's native classes ( I tested using .net 6.0 )以上也可以使用 .net 的本机类中的System.Text.Json.Nodes命名空间来实现(我使用 .net 6.0 进行了测试)

Intead of JObject use JsonObject and instead of JArray use JsonArray and to get json output, use ToJsonString() method on the object JObject使用JsonObject而不是JArray使用JsonArray并获取 json 输出,在对象上使用ToJsonString()方法

There's JsonWriter , which is not much more than StringBuilder - you do not get much constraints and can possibly end up with incorrect documentJsonWriter ,它并不比StringBuilder多多少——你没有太多的限制,并且可能最终得到不正确的文档

Some time ago I wanted to create simple documents WITHOUT the overhead of serialization, but with the guarantee they will be correct.前段时间我想创建没有序列化开销的简单文档,但要保证它们是正确的。

The pattern I went with is:我使用的模式是:

var doc = JSONElement.JSONDocument.newDoc(true);

using (var root = doc.addObject())
{
    root.addString("firstName", "John");
    root.addString("lastName", "Smith");
    root.addBoolean("isAlive", true);
    root.addNumber("age", 27);
    using (var addres = root.addObject("address"))
    {
        addres.addString("streetAddress", "21 2nd Street");
        addres.addString("city", "New York");
        addres.addString("state", "NY");
        addres.addString("postalCode", "10021-3100");
    }
    using (var phoneNumbers = root.addArray("phoneNumbers"))
    {
        using (var phone = phoneNumbers.addObject())
        {
            phone.addString("type", "home");
            phone.addString("number", "212 555-1234");
        }
//[....]           
    }        
}
string output = doc.getOutput();

} }

The module (< 300lines) is available here: https://github.com/AXImproveLtd/jsonDocCreate该模块(< 300 行)可在此处获得: https ://github.com/AXImproveLtd/jsonDocCreate

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

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