如何在没有JSON.NET库的情况下解析JSON?

k5ifujac  于 2023-03-13  发布在  .NET
关注(0)|答案(8)|浏览(181)

我试图在Visual Studio 2011上为Windows 8构建一个Metro应用程序。当我试图这样做时,我遇到了一些关于如何在没有JSON.NET库的情况下解析JSON的问题(它还不支持Metro应用程序)。
不管怎样,我想解析这个:

{
   "name":"Prince Charming",
   "artist":"Metallica",
   "genre":"Rock and Metal",
   "album":"Reload",
   "album_image":"http:\/\/up203.siz.co.il\/up2\/u2zzzw4mjayz.png",
   "link":"http:\/\/f2h.co.il\/7779182246886"
}
0x6upsns

0x6upsns1#

您可以使用在.NET 4.5中添加的System.Json Namespace中的类。您需要添加对System.Runtime.Serialization程序集的引用
JsonValue.Parse() Method解析JSON文本并返回JsonValue

JsonValue value = JsonValue.Parse(@"{ ""name"":""Prince Charming"", ...");

如果用JSON对象传递一个字符串,则应该能够将该值强制转换为JsonObject

using System.Json;

JsonObject result = value as JsonObject;

Console.WriteLine("Name .... {0}", (string)result["name"]);
Console.WriteLine("Artist .. {0}", (string)result["artist"]);
Console.WriteLine("Genre ... {0}", (string)result["genre"]);
Console.WriteLine("Album ... {0}", (string)result["album"]);

这些类与System.Xml.Linq Namespace中的类非常相似。

dgsult0t

dgsult0t2#

我使用这个......但是从来没有做过任何metro应用程序开发,所以我不知道对您可用的库有任何限制。(注意,您需要将您的类标记为具有DataContract和DataMember属性)

public static class JSONSerializer<TType> where TType : class
{
    /// <summary>
    /// Serializes an object to JSON
    /// </summary>
    public static string Serialize(TType instance)
    {
        var serializer = new DataContractJsonSerializer(typeof(TType));
        using (var stream = new MemoryStream())
        {
            serializer.WriteObject(stream, instance);
            return Encoding.Default.GetString(stream.ToArray());
        }
    }

    /// <summary>
    /// DeSerializes an object from JSON
    /// </summary>
    public static TType DeSerialize(string json)
    {
        using (var stream = new MemoryStream(Encoding.Default.GetBytes(json)))
        {
            var serializer = new DataContractJsonSerializer(typeof(TType));
            return serializer.ReadObject(stream) as TType;
        }
    }
}

所以,如果你有这样的课...

[DataContract]
public class MusicInfo
{
    [DataMember]
    public string Name { get; set; }

    [DataMember]
    public string Artist { get; set; }

    [DataMember]
    public string Genre { get; set; }

    [DataMember]
    public string Album { get; set; }

    [DataMember]
    public string AlbumImage { get; set; }

    [DataMember]
    public string Link { get; set; }

}

然后你会这样使用它...

var musicInfo = new MusicInfo
{
     Name = "Prince Charming",
     Artist = "Metallica",
     Genre = "Rock and Metal",
     Album = "Reload",
     AlbumImage = "http://up203.siz.co.il/up2/u2zzzw4mjayz.png",
     Link = "http://f2h.co.il/7779182246886"
};

// This will produce a JSON String
var serialized = JSONSerializer<MusicInfo>.Serialize(musicInfo);

// This will produce a copy of the instance you created earlier
var deserialized = JSONSerializer<MusicInfo>.DeSerialize(serialized);
zf2sa74q

zf2sa74q3#

对于那些没有4.5的人,这里是我的库函数,读取json。它需要一个项目引用System.Web.Extensions

using System.Web.Script.Serialization;

public object DeserializeJson<T>(string Json)
{
    JavaScriptSerializer JavaScriptSerializer = new JavaScriptSerializer();
    return JavaScriptSerializer.Deserialize<T>(Json);
}

通常,json是基于一个合约编写的,这个合约可以而且通常会被编码成一个类(T),有时你可以从json中取出一个词,然后在对象浏览器中搜索这个类型。
示例用法:
给定json

{"logEntries":[],"value":"My Code","text":"My Text","enabled":true,"checkedIndices":[],"checkedItemsTextOverflows":false}

你可以把它解析成一个RadComboBoxClientState对象,如下所示:

string ClientStateJson = Page.Request.Form("ReportGrid1_cboReportType_ClientState");
RadComboBoxClientState RadComboBoxClientState = DeserializeJson<RadComboBoxClientState>(ClientStateJson);
return RadComboBoxClientState.Value;
ajsxfq5m

ajsxfq5m4#

我需要一个JSON序列化器和反序列化器,没有任何第三方依赖项或nuget,可以支持旧系统,所以您不必根据目标平台在Newtonsoft.Json、System.Text.Json、DataContractSerializer、JavaScriptSerializer等之间进行选择。
所以我在这里开始了这个开源(MIT)项目:
https://github.com/smourier/ZeroDepJson
它只是一个C#文件ZeroDepJson.cs,兼容.NET框架4.x到.NET核心,以及.NET 5.
注意,它可能不如前面提到的所有库(特别是在性能方面),但它应该是相当不错的,没有摩擦。

42fyovps

42fyovps5#

你用过JavaScriptSerializer吗?还有DataContractJsonSerializer

vu8f3i0k

vu8f3i0k6#

我已经写了一个小的构造来做这个很久以前,它需要**System.Runtime.Serialization.Json**命名空间。它使用DataContractJsonSerializer序列化和反序列化object与静态方法JConvert
它适用于小数据集,但尚未测试大数据源。

JsonHelper.cs

// Json Serializer without NewtonSoft
public static class JsonHelper
{
    public static R JConvert<P,R>(this P t)
    {       
        if(typeof(P) == typeof(string))
        {
            var return1 =  (R)(JsonDeserializer<R>(t as string));
            return return1;
        }
        else
        {
            var return2 =  (JsonSerializer<P>(t));
            R result = (R)Convert.ChangeType(return2, typeof(R));
            return result;
        }   
    }
    
    private static String JsonSerializer<T>(T t)
    {
        var stream1 = new MemoryStream();
        var ser = new DataContractJsonSerializer(typeof(T));
        ser.WriteObject(stream1, t);
        stream1.Position = 0;
        var sr = new StreamReader(stream1);     
        return (sr.ReadToEnd());
    }
    
    private static T JsonDeserializer<T>(string jsonString)
    {
        T deserializedUser = default(T);
        var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
        var ser = new DataContractJsonSerializer(typeof(T));
        deserializedUser = (T)ser.ReadObject(ms);// as T;
        ms.Close();
        return deserializedUser;
    }
}

语法:

要使用JsonHelper,您需要调用

JConvert<string,object>(str); //to Parse string to non anonymous <object>
JConvert<object,string>(obj); //to convert <obj> to string

示例:

假设我们有一个类person

public class person
{
    public string FirstName {get;set;}
    public string LastName {get;set;}
}

var obj = new person();//"vinod","srivastav");
obj.FirstName = "vinod";
obj.LastName = "srivastav";

要转换person对象,我们可以调用:

var asText = JsonHelper.JConvert<person,string>(obj); //to convert <obj> to string

var asObject = JsonHelper.JConvert<string,person>(asText); //to convert string to non-anonymous object

编辑日期:2023年

由于&结构有点难以使用和理解,下面是另一个简单的实现,用JSON.stringify()JSON.parse()模拟Javascript JSON对象

public class JSON
{
    public static String Stringify<T>(T t)
    {
        var inmemory = new MemoryStream();
        var ser = new DataContractJsonSerializer(typeof(T));
        ser.WriteObject(inmemory, t);
        return (Encoding.UTF8.GetString(inmemory.ToArray()));
    }
    
    public static T Parse<T>(string jsonString)
    {
        T deserializedUser = default(T);
        var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
        var ser = new DataContractJsonSerializer(typeof(T));
        deserializedUser = (T)ser.ReadObject(ms);// as T;
        ms.Close();
        return deserializedUser;
    }
}

现在,要使用这个方法,您只需编写:

//to convert <obj> to string
var asText = JSON.Stringify(obj); 

/to convert string to non-anonymous object
var asObject = JSON.Parse<person>(asText); /
kpbwa7wx

kpbwa7wx7#

您可以使用DataContractJsonSerializer。有关详细信息,请参阅此link

to94eoyn

to94eoyn8#

using System;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;

namespace OTL
{
    /// <summary>
    /// Before usage: Define your class, sample:
    /// [DataContract]
    ///public class MusicInfo
    ///{
    ///   [DataMember(Name="music_name")]
    ///   public string Name { get; set; }
    ///   [DataMember]
    ///   public string Artist{get; set;}
    ///}
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class OTLJSON<T> where T : class
    {
        /// <summary>
        /// Serializes an object to JSON
        /// Usage: string serialized = OTLJSON&lt;MusicInfo&gt;.Serialize(musicInfo);
        /// </summary>
        /// <param name="instance"></param>
        /// <returns></returns>
        public static string Serialize(T instance)
        {
            var serializer = new DataContractJsonSerializer(typeof(T));
            using (var stream = new MemoryStream())
            {
                serializer.WriteObject(stream, instance);
                return Encoding.Default.GetString(stream.ToArray());
            }
        }

        /// <summary>
        /// DeSerializes an object from JSON
        /// Usage:  MusicInfo deserialized = OTLJSON&lt;MusicInfo&gt;.Deserialize(json);
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static T Deserialize(string json)
        {
            if (string.IsNullOrEmpty(json))
                throw new Exception("Json can't empty");
            else
                try
                {
                    using (var stream = new MemoryStream(Encoding.Default.GetBytes(json)))
                    {

                        var serializer = new DataContractJsonSerializer(typeof(T));
                        return serializer.ReadObject(stream) as T;
                    }
                }
                catch (Exception e)
                {
                    throw new Exception("Json can't convert to Object because it isn't correct format.");
                }
        }
    }
}

相关问题