I have an object model that looks like this:
public MyObjectInJson
{
public long ObjectID {get;set;}
public string ObjectInJson {get;set;}
}
The property ObjectInJson is an already serialized version an object that contains nested lists. For the moment, I’m serializing the list of MyObjectInJson manually like this:
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();
I wonder if I can replace this sort of dangerous code with JavascriptSerializer and get the same results.
How would I do this?
If using .Net 6.0 or later;
Default to using the built in
System.Text.Jsonparser implementation with Source Generation. Its a little more typing and compiling but, is more efficient at runtime.The "easier to code" option below, still works but, less efficiently because it uses Reflection at runtime. The new method has some intentional, by design limitations. If you can’t change your model to avoid those, the Reflection based method remains available.
e.g.
If using .Net Core 3.0 to .Net 5.0, it is time to upgrade;
Default to using the built in
System.Text.Jsonparser implementation.e.g.
If stuck using .Net Core 2.2 or earlier;
Default to using Newtonsoft JSON.Net as your first choice JSON Parser.
e.g.
you may need to install the package first.
For more details see and upvote the answer that is the source of this information.
For reference only, this was the original answer, many years ago;