简体   繁体   中英

Json Serializer for .netcore ant .Net3.5

Is there any json serializer library that work in .netcore and .Net3.5?

I need to use a library in a multiplatform project the problem is that Newtonsoft's library works only in .Net Framework and System.Text.Json only works in .netcore.

** I tried Json.Net but no luck. I get this kind of error on all of the libraries:

在此处输入图片说明

You can use DataContractJsonSerializer

I am using it in my .net standard library to serialize and de-serialize my model objects to json.

public static string PrepareJsonString<T>(object objectToBeParsed)
    {
        DataContractJsonSerializer dataContractSerializer = new DataContractJsonSerializer(typeof(T));
        string json = string.Empty;
        using (var ms = new MemoryStream())
        {
            dataContractSerializer.WriteObject(ms, (T)objectToBeParsed);
            ms.Position = 0;
            StreamReader sr = new StreamReader(ms);
            json = sr.ReadToEnd();
        }

        return json;
    }

public static object PrepareObjectFromString<T>(string json)
    {
        DataContractJsonSerializer dataContractSerializer = new DataContractJsonSerializer(typeof(T));
        using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
        {
            var deSerializedUser = dataContractSerializer.ReadObject(memoryStream);
            return deSerializedUser;
        }
    }

sample to consume this functions

List<MyModel>  list=  PrepareObjectFromString<List<MyModel>>(myJson);
                       or
MyModel  list=  PrepareObjectFromString<MyModel>(myJson);

string json=PrepareJsonString<MyModel>(myModelInstance);

Hope this helps.

Thank you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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