Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

c# - 在C#中使用JavaScriptSerializer将JSON转换为XML(Convert JSON to XML using JavaScriptSerializer in c#)

I have a JSON structure like below.

(我有一个如下的JSON结构。)

json={
    "page": {
        "mode": "2",
        "ref": "user"
    }
}

I am using the following code for converting JSON to XML.

(我正在使用以下代码将JSON转换为XML。)

Reference: http://www.flowgearcoder.net/2013/04/03/convert-between-json-and-xml

(参考: http//www.flowgearcoder.net/2013/04/03/convert-between-json-and-xml)

  var dynamicObject = new System.Web.Script.Serialization.JavaScriptSerializer().DeserializeObject(Json);
        System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(dynamicObject.GetType());

        MemoryStream ms = new MemoryStream();
        serializer.Serialize(ms, dynamicObject);

        Xml = System.Text.Encoding.UTF8.GetString(ms.ToArray());

I am getting the following error while executing the xmlSerializer conversion.

(执行xmlSerializer转换时出现以下错误。)

The type System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089], [System.Object, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] is not supported because it implements IDictionary.

(类型System.Collections.Generic.Dictionary`2 [[System.String,mscorlib,Version = 2.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089],[System.Object,mscorlib,Version = 2.0.0.0,Culture = neutral ,PublicKeyToken = b77a5c561934e089]不支持,因为它实现了IDictionary。)

Can anyone help me figure out this issue?

(谁能帮我解决这个问题?)

  ask by Tom Cruise translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

JavaScriptSerializer.DeserializeObject cast json string to Dictionary<String, Object> .

(JavaScriptSerializer.DeserializeObject将json字符串转换为Dictionary<String, Object> 。)

Dictionary is not supported by XMLSerializer.

(XMLSerializer不支持字典。)

So if you're creating json yourself, you might want to change its structure and use JavaScriptSerializer.Deserialize<T> method to cast it to specific class and latter serialize it to XML.

(因此,如果您自己创建json,则可能需要更改其结构,并使用JavaScriptSerializer.Deserialize<T>方法将其转换为特定的类,然后将其序列化为XML。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...