我有一个对象模型,看起来像这样:
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替换这种危险的代码,并得到相同的结果。
我该怎么做呢?
我尝试了这里的其他答案来序列化POST请求的参数,但我的后端不喜欢这样一个事实,即我正在发送数组的字符串版本。我不想总是检查参数的类型是否为字符串并将其转换为数组。
我使用的是Json。NET(现在已内置到c#中),我将List转换为一个数组,并让转换器处理其余的工作。
public class MyObjectInJson
{
public long ID;
public OtherObject[] array;
}
可以使用List . toarray()将List转换为数组;
最后使用JsonConvert,你可以把整个对象变成一个字符串:
string jsonString = JsonConvert.SerializeObject(objectInJson);
希望这能帮助到其他人。
我尝试了这里的其他答案来序列化POST请求的参数,但我的后端不喜欢这样一个事实,即我正在发送数组的字符串版本。我不想总是检查参数的类型是否为字符串并将其转换为数组。
我使用的是Json。NET(现在已内置到c#中),我将List转换为一个数组,并让转换器处理其余的工作。
public class MyObjectInJson
{
public long ID;
public OtherObject[] array;
}
可以使用List . toarray()将List转换为数组;
最后使用JsonConvert,你可以把整个对象变成一个字符串:
string jsonString = JsonConvert.SerializeObject(objectInJson);
希望这能帮助到其他人。
建立在另一个帖子的答案上。我提出了一个更通用的方法来构建一个列表,利用动态检索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));
}