Systen.Text.Json .Net STandard 2.0

Has anyone had any luck getting this into Unity 2021.2? Or any Unity version that supports .Net Standard 2.0?

When I get the package and drop the dll and xml in, all I get is

Unable to resolve reference ‘System.Text.Encodings.Web’. Is the assembly missing or incompatible with the current platform?

just a little search whether it is implemented or not using Google with the keywords “Unity System.Text.Json” and you’ll stumble upon this thread

As far as I can read out of that thread, there are some complications with supporting System.Text.Json.

There are alternatives like Newtonsoft Json though. Some of the packages that Unity uses, even rely on newtonsoft json which is why they’ve made a package of it.
Package Manager → + → Add by name → com.unity.nuget.newtonsoft-json

3 Likes

But I am not interested in the Newtonsoft package, it is a security risk with objects, that I don’t want to use. I have read other forum posts in here where people have got the Systen.Text.Json .Net Standard 2.0 version to work in Unity, so now I am asking how they did it.

Is there a .Net Standard 2.0 version of this library? Because the MSDN says there isn’t.
7811298--987909--screenshot.png

Yes there is.

Scroll down to how to get the library!

Ah nuget package. Well, good luck with that. You probably will have problems with the Memory and the Buffers modules too. At least I had last time I tried.

To use System.text.json you need to download all it dependencies into too:

  • Microsoft.Bcl.AsyncInterfaces (NET Standard 2.1 version if you on Unity 2021.2)
  • System.Buffers (not required if you on Unity 2021.2)
  • System.Memory (not required if you on Unity 2021.2)
  • System.Numerics.Vectors (not required if you on Unity 2021.2)
  • System.Runtime.CompilerServices.Unsafe
  • System.Text.Encodings.Web
  • System.Threading.Tasks.Extensions (not required if you on Unity 2021.2)

with all this libraries you should be able to use System.Text.Json.

but it still may have issues with il2cpp

You should consider being more selective about where you get your nonsense from.

I have code that I have serialize as objects, and it is a security risk. Do you mind showing me where it is not?

NewtonSoft is kind of an industry standard for JSON. It’s likely no more or less secure than the operating system context it is running within.

Are you perhaps thinking of binary formatter???

https://docs.microsoft.com/en-us/dotnet/standard/serialization/binaryformatter-security-guide

Do not use the binary formatter/serializer: it is insecure, it cannot be made secure, and it makes debugging very difficult, plus it actually will NOT prevent people from modifying your save data on their computers.

but how using System.Text.Json will eliminate security risk?
System.text.json us not more secure than Newtonsoft.Json. it was created for better perfomance and to have Json serialize within System libraries

No I am not.

For the ability to serialise this

Dictionary<string, object>

You have to have the types stored into the json, which is done as serialising an object, everything I have found on this, says Json.Net has a security flaw if you use the type in the Json. This is defined by OWASP as a security flaw.

If you have a way to do this safely, I am all ears!

Yet, I can safely serialise Objects like a Dictionary<string, object> with MS way, and yet I can’t with Json.Net safely. If you have a way to do this safely, I am all ears!

Don’t use JSON in production. Problem solved. It’s great for debugging, but nothing else. It’s insane arguing which crappy JSON is more secure.

Json, XML, Object

It has to be done, it is part of my data structure!

Okay, if we’re moving targets: do not use text-based serialization in production. No, it’s not ‘has to be’ done, you chose it.

It has to be done, there is no way around the data structure.

Unless you have a workaround that can be done safely, then I need a solution that works!

one of solutions could be to implement custom converter that will encode type information but not in json string but not so “transparent” as it done by default and limit possible types.
for example some something like this

public static class Program
    {
        public static void Main()
        {
           var converter = new CustomConverter();
           var data = new Dictionary<string, object>
           {
                  ["1"] = new DerivedClass() { Data = 42, Data2 = 24 }
           };
          
           var str = JsonConvert.SerializeObject(data, converter);
           Console.WriteLine(str);
           var dictionary = JsonConvert.DeserializeObject<Dictionary<string,object>>(str, converter);
           var obj = (DerivedClass)dictionary["1"];
           Console.WriteLine(obj.Data);
           Console.WriteLine(obj.Data2);
        }
    }
   
    public class CustomConverter : JsonConverter
    {
        public enum TypeCode
        {
            Base = 1,
            Derived = 2,
        }
       
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var jObject = (JObject)JToken.FromObject(value);
            jObject.AddFirst(new JProperty("TypeCode", GetTypeCode(value)));
            jObject.WriteTo(writer);
        }
       
        private int GetTypeCode(object value)
        {
            if (value.GetType() == typeof(BaseClass))
                return (int)TypeCode.Base;
            if (value.GetType() == typeof(DerivedClass))
            return (int)TypeCode.Derived;
               
            throw new ArgumentException($"Type {value.GetType()} is not supported");
        }
       
        private object GetEmptyInstance(int typeCode)
        {
            return (TypeCode)typeCode switch
            {
                TypeCode.Base => new BaseClass(),
                TypeCode.Derived => new DerivedClass()
            };
        }
       
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var jObject = JObject.Load(reader);
            var type = (int?)jObject["TypeCode"];
            if (type == null)
                throw new ArgumentException("Input data does not contains type code");
               
            var instance = GetEmptyInstance((int)type);
            serializer.Populate(jObject.CreateReader(), instance);
           
            return instance;
        }
       
        public override bool CanConvert(Type objectType)
        {
            return typeof(BaseClass).IsAssignableFrom(objectType) || objectType == typeof(object);
        }
    }
   
    public class BaseClass
    {
        public int Data { get; set; }
    }
   
    public class DerivedClass : BaseClass
    {
        public int Data2 { get; set; }
    }

Also I believe that almos any System.Text.Json solution could be ported to Json.NET, because as far as I know Json.NET has almost all features System.Text.Json and more

This is why I am looking for a solution to getting System.Text,Json into Unity 2021.2, the problem with Json.Net, is that the object can still be delivered a payload that is malicious.

Just curious. how did you implement serialization/deserialization of Dictionary<string, object> with System.Text.Json in more secure way than it possible with Json.NET?