我有一个对象模型,看起来像这样:

public MyObjectInJson
{
   public long ObjectID {get;set;}
   public string ObjectInJson {get;set;}
}

属性objectjson是一个包含嵌套列表的对象的已序列化版本。目前,我手动序列化myobjectjson的列表,就像这样:

StringBuilder TheListBuilder = new StringBuilder();

TheListBuilder.Append("[");
int TheCounter = 0;

foreach (MyObjectInJson TheObject in TheList)
{
  TheCounter++;
  TheListBuilder.Append(TheObject.ObjectInJson);

  if (TheCounter != TheList.Count())
  {
    TheListBuilder.Append(",");
  }
}
TheListBuilder.Append("]");

return TheListBuilder.ToString();

我想知道我是否可以用JavascriptSerializer替换这种危险的代码,并得到相同的结果。 我该怎么做呢?


当前回答

建立在另一个帖子的答案上。我提出了一个更通用的方法来构建一个列表,利用动态检索Json。NET版本12.x

using Newtonsoft.Json;

static class JsonObj
{
    /// <summary>
    /// Deserializes a json file into an object list
    /// Author: Joseph Poirier 2/26/2019
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="fileName"></param>
    /// <returns></returns>
    public static List<T> DeSerializeObject<T>(string fileName)
    {
        List<T> objectOut = new List<T>();

        if (string.IsNullOrEmpty(fileName)) { return objectOut; }

        try
        {
            // reading in full file as text
            string ss = File.ReadAllText(fileName);

            // went with <dynamic> over <T> or <List<T>> to avoid error..
            //  unexpected character at line 1 column 2
            var output = JsonConvert.DeserializeObject<dynamic>(ss);

            foreach (var Record in output)
            {
                foreach (T data in Record)
                {
                    objectOut.Add(data);
                }
            }
        }
        catch (Exception ex)
        {
            //Log exception here
            Console.Write(ex.Message);
        }

        return objectOut;
    }
}

调用流程

{
        string fname = "../../Names.json"; // <- your json file path

        // for alternate types replace string with custom class below
        List<string> jsonFile = JsonObj.DeSerializeObject<string>(fname);
}

或者这个process调用

{
        string fname = "../../Names.json"; // <- your json file path

        // for alternate types replace string with custom class below
        List<string> jsonFile = new List<string>();
        jsonFile.AddRange(JsonObj.DeSerializeObject<string>(fname));
}

其他回答

public static string JSONSerialize<T>(T obj)
        {
            string retVal = String.Empty;
            using (MemoryStream ms = new MemoryStream())
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
                serializer.WriteObject(ms, obj);
                var byteArray = ms.ToArray();
                retVal = Encoding.UTF8.GetString(byteArray, 0, byteArray.Length);
            }
            return retVal;
        }

建立在另一个帖子的答案上。我提出了一个更通用的方法来构建一个列表,利用动态检索Json。NET版本12.x

using Newtonsoft.Json;

static class JsonObj
{
    /// <summary>
    /// Deserializes a json file into an object list
    /// Author: Joseph Poirier 2/26/2019
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="fileName"></param>
    /// <returns></returns>
    public static List<T> DeSerializeObject<T>(string fileName)
    {
        List<T> objectOut = new List<T>();

        if (string.IsNullOrEmpty(fileName)) { return objectOut; }

        try
        {
            // reading in full file as text
            string ss = File.ReadAllText(fileName);

            // went with <dynamic> over <T> or <List<T>> to avoid error..
            //  unexpected character at line 1 column 2
            var output = JsonConvert.DeserializeObject<dynamic>(ss);

            foreach (var Record in output)
            {
                foreach (T data in Record)
                {
                    objectOut.Add(data);
                }
            }
        }
        catch (Exception ex)
        {
            //Log exception here
            Console.Write(ex.Message);
        }

        return objectOut;
    }
}

调用流程

{
        string fname = "../../Names.json"; // <- your json file path

        // for alternate types replace string with custom class below
        List<string> jsonFile = JsonObj.DeSerializeObject<string>(fname);
}

或者这个process调用

{
        string fname = "../../Names.json"; // <- your json file path

        // for alternate types replace string with custom class below
        List<string> jsonFile = new List<string>();
        jsonFile.AddRange(JsonObj.DeSerializeObject<string>(fname));
}

您也可以使用Json.NET。只需在http://james.newtonking.com/pages/json-net.aspx上下载它,提取压缩文件并添加它作为参考。

然后只需序列化列表(或任何你想要的对象)如下:

using Newtonsoft.Json;

string json = JsonConvert.SerializeObject(listTop10);

更新:您也可以将它添加到您的项目通过NuGet包管理器(工具-> NuGet包管理器->包管理器控制台):

PM> Install-Package Newtonsoft.Json

文档:序列化集合

我尝试了这里的其他答案来序列化POST请求的参数,但我的后端不喜欢这样一个事实,即我正在发送数组的字符串版本。我不想总是检查参数的类型是否为字符串并将其转换为数组。

我使用的是Json。NET(现在已内置到c#中),我将List转换为一个数组,并让转换器处理其余的工作。

public class MyObjectInJson 
{
    public long ID;
    public OtherObject[] array;
}

可以使用List . toarray()将List转换为数组;

最后使用JsonConvert,你可以把整个对象变成一个字符串:

string jsonString = JsonConvert.SerializeObject(objectInJson);

希望这能帮助到其他人。

如果你在asp的上下文中做这个。Net Core API动作,到Json的转换是隐式完成的。

[HttpGet]
public ActionResult Get()
{
    return Ok(TheList);
}