本文介绍了ServiceStack.Text.JsonObject.Parse与NewtonSoft.Json.Linq.JObject.Parse是否可用于“动态"实例的嵌套树?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想尝试ServiceStack的json解析,但是我已经想出了如何通过Newtonsoft做我需要的事情.可以通过ServiceStack完成同一件事吗?

I'd like to try ServiceStack's json parsing, but I've already figured out how to do something I need via Newtonsoft. Can this same thing by done via ServiceStack?

我尝试使用注释掉的代码,但是它提供了异常,请参阅下面的异常详细信息.

I've tried with the commented out code but it gives exceptions, see below for exception details.

谢谢!

乔什

    [Test]
    public void TranslateFromGitHubToCommitMessage()
    {
        const string json =
@"
{
'commits': 
[
    {
      'author': {
        'email': '[email protected]',
        'name': 'The Null Developer'
      },
      'message': 'okay i give in'
    },
    {
      'author': {
        'email': '[email protected]',
        'name': 'Doc U. Mentation'
      },
      'message': 'Updating the docs, that\'s my job'
    },
    {
      'author': {
        'email': '[email protected]',
        'name': 'Doc U. Mentation'
      },
      'message': 'Oops, typos'
    }
]
}
";
        dynamic root = JObject.Parse(json);
        //dynamic root = ServiceStack.Text.JsonSerializer.DeserializeFromString<JsonObject>(json);
        //dynamic root = ServiceStack.Text.JsonObject.Parse(json);

        var summaries = new List<string>();

        foreach (var commit in root.commits)
        {
            var author = commit.author;
            var message = commit.message;
            summaries.Add(string.Format("{0} <{1}>: {2}", author.name, author.email, message));
        }            

        const string expected1 = "The Null Developer <[email protected]>: okay i give in";
        const string expected2 = "Doc U. Mentation <[email protected]>: Updating the docs, that's my job";
        const string expected3 = "Doc U. Mentation <[email protected]>: Oops, typos";

        Assert.AreEqual(3, summaries.Count);
        Assert.AreEqual(expected1, summaries[0]);
        Assert.AreEqual(expected2, summaries[1]);
        Assert.AreEqual(expected3, summaries[2]);
    }

例外详细信息

使用第一条注释掉的行时:

When using the first commented out line:

dynamic root = ServiceStack.Text.JsonSerializer.DeserializeFromString<JsonObject>(json);

调用该方法时会发生此异常.

This exception occurs when the method is called.

NullReferenceException:

NullReferenceException:

at ServiceStack.Text.Common.DeserializeListWithElements`2.ParseGenericList(String value, Type      createListType, ParseStringDelegate parseFn)
at ServiceStack.Text.Common.DeserializeEnumerable`2.<>c__DisplayClass3.<GetParseFn>b__0(String value)
at ServiceStack.Text.Common.DeserializeSpecializedCollections`2.<>c__DisplayClass7.  <GetGenericEnumerableParseFn>b__6(String x)
at ServiceStack.Text.Json.JsonReader`1.Parse(String value)
at ServiceStack.Text.JsonSerializer.DeserializeFromString[T](String value)
at GitHubCommitAttemptTranslator.Tests.GitHubCommitAttemptTranslatorTests.TranslateFromGitHubToCommitMessage()

第二个:

dynamic root = ServiceStack.Text.JsonObject.Parse(json);

var summaries = new List<string>();

foreach (var commit in root.commits) // <-- Happens here

'ServiceStack.Text.JsonObject'不包含'commits'的定义

'ServiceStack.Text.JsonObject' does not contain a definition for 'commits'

注意:如果我使用第一行中的代码,但将类型更改为或而不是

Note: the message is 'string' does not contain a definition for 'commits' if I use code from line one, but change the type to or to instead of

at CallSite.Target(Closure , CallSite , Object )
at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
at GitHubCommitAttemptTranslator.Tests.GitHubCommitAttemptTranslatorTests.TranslateFromGitHubToCommitMessage()

从.NET 4.0 ServiceStack使用DynamicJson后

引用神话的评论:此测试用例有效,但是如果我将其修改如下:

Referring to mythz's comment: This test case works, but if I modify it like below:

var dog = new { Name = "Spot", Parts = new { Part1 = "black", Part2 = "gray" }, Arr = new [] { "one", "two", "three"} };
var json = DynamicJson.Serialize(dog);
var deserialized = DynamicJson.Deserialize(json);

然后反序列化.Name和Parts都可以,但是Arr是字符串类型.

Then, deserialized.Name and Parts are fine, but Arr is of type string.

也:

如果我使用'引号,它似乎无法正常工作.那是正常的吗? json2可以工作(在某种程度上Arr仍然是字符串),但是json3根本不工作.它只是返回

If I use ' quotes it doesn't appear to work. Is that normal? json2 works (to the degree that Arr is also still a string), but json3 does not work at all. It just returns

Immediate Window:

deserialized = DynamicJson.Deserialize(json3);
{}
base {System.Dynamic.DynamicObject}: {}
_hash: Count = 1

----- code: -----
        var json2 =
            @"
        {
          ""Name"": ""Spot"",
          ""Parts"": {
            ""Part1"": ""black"",
            ""Part2"": ""gray""
          },
          ""Arr"": [
            ""one"",
            ""two"",
            ""three""
          ]
        }";

        var json3 =
            @"
        {
          'Name': 'Spot',
          'Parts': {
            'Part1': 'black',
            'Part2': 'gray'
          },
          'Arr': [
            'one',
            'two',
            'three'
          ]
        }";

        var deserialized = DynamicJson.Deserialize(json1);            

推荐答案

ServiceStack的JSON序列化器还支持动态解析,请参见动态JSON部分.

ServiceStack's JSON Serializer also supports dynamic parsing, see examples of how to parse GitHub's JSON in the Dynamic JSON section of the wiki page.

这篇关于ServiceStack.Text.JsonObject.Parse与NewtonSoft.Json.Linq.JObject.Parse是否可用于“动态"实例的嵌套树?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-25 05:36