无法找到类型为 System.Json.JsonObject 的默认构造函数。

3

我正在尝试获取一些Twitter数据,但是无法完成我的任务。

using System.Collections.Generic;
using System.Json;
using System.Linq;
using System.Net.Http;
using System.Web.Mvc;
using Demo.Models;

namespace Demo.Controllers
{
    public class HomeController : Controller
    {
    public ActionResult Index()
            {
                var model = new List<Tweets>();
                var client = new HttpClient();
                var task =
                    client.GetAsync("http://search.twitter.com/search.json?q=dave").ContinueWith((taskWithMessage) =>
                        {
                            var response = taskWithMessage.Result;
                            var jsonTask = response.Content.ReadAsAsync<JsonObject>();
                            jsonTask.Wait(); //THIS IS WHERE THE FAULT IS

                            var jsonObject = jsonTask.Result;
                            model.AddRange(
                                (from JsonObject jo in jsonObject["results"]
                                 select new Tweets
                                     {
                                         Name = jo["from_user"].ToString(),
                                         Text = jo["text"].ToString()
                                     }
                                ));
                        });

                task.Wait();
                return View(model);
            }
    }
}

当我执行以上代码时,它会失败,并显示以下错误信息:
无法找到用于类型 System.Json.JsonObject 的默认构造函数。
我在使用 .NET 4 和 4.5 时也遇到了相同的错误信息。
请问有人能够解释并告诉我需要做什么吗?
以下是完整的堆栈跟踪信息。
[JsonSerializationException: Unable to find a default constructor to use for type System.Json.JsonObject. Path 'completed_in', line 1, position 16.]  
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateNewDictionary(JsonReader reader, JsonDictionaryContract contract) +234
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue) +810   


    Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateValueInternal(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue) +184
Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent) +793
Newtonsoft.Json.JsonSerializer.DeserializeInternal(JsonReader reader, Type objectType) +1143
Newtonsoft.Json.JsonSerializer.Deserialize(JsonReader reader, Type objectType) +46
System.Net.Http.Formatting.<>c_DisplayClass8.b_6() +950 System.Threading.Tasks.TaskHelpers.RunSynchronously(Func`1 func, CancellationToken cancellationToken) +143


    [AggregateException: One or more errors occurred.]
System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions) +3548265
System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken) +10487717
System.Threading.Tasks.Task.Wait() +10
Demo.Controllers.<>c_DisplayClass3.b_1(Task1 taskWithMessage) in c:\Users\Dave\Documents\Visual Studio 2012\Projects\Demo\Demo\Controllers\HomeController.cs:22
System.Threading.Tasks.ContinuationTaskFromResultTask1.InnerInvoke() +80 System.Threading.Tasks.Task.Execute() +49


     [AggregateException: One or more errors occurred.]
System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions) +3548265
System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken) +10487717
System.Threading.Tasks.Task.Wait() +10
Demo.Controllers.HomeController.Index() in c:\Users\Dave\Documents\Visual Studio 2012\Projects\Demo\Demo\Controllers\HomeController.cs:35
lambda_method(Closure , ControllerBase , Object[] ) +101
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) +211
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) +27
System.Web.Mvc.Async.<>c_DisplayClass42.b_41() +28 System.Web.Mvc.Async.<>c_DisplayClass81.<BeginSynchronous>b__7(IAsyncResult _) +10 System.Web.Mvc.Async.WrappedAsyncResult1.End() +57 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +48
System.Web.Mvc.Async.<>c_DisplayClass39.b_33() +57 System.Web.Mvc.Async.<>c_DisplayClass4f.b_49() +223 System.Web.Mvc.Async.<>c_DisplayClass37.b_36(IAsyncResult asyncResult) +10 System.Web.Mvc.Async.WrappedAsyncResult1.End() +57 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +48
System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +24 System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +102 System.Web.Mvc.Async.WrappedAsyncResult1.End() +57 System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +43
System.Web.Mvc.<>c_DisplayClass1d.b_18(IAsyncResult asyncResult) +14
System.Web.Mvc.Async.<>c_DisplayClass4.b_3(IAsyncResult ar) +23 System.Web.Mvc.Async.WrappedAsyncResult1.End() +62
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +57 System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23 System.Web.Mvc.Async.WrappedAsyncResult1.End() +62
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +47     System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c_DisplayClass8.b_3(IAsyncResult asyncResult) +25
System.Web.Mvc.Async.<>c_DisplayClass4.b__3(IAsyncResult ar) +23 System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +47 System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9     System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9629708 System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

JsonObject 是你创建的类吗? - Conrad Lotz
不,它是System.Json的一部分。 - Dave
1个回答

3
这是因为JsonObject没有默认构造函数。请参见这里
我建议使用Newtonsoft.Json(在nuget中称为“JSON.NET”)而不是System.Json。
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using PayPoint.Models;
using System.Threading.Tasks;

namespace PayPoint.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var model = new List<Tweets>();
            const string webUri = "http://search.twitter.com/search.json?q=dave";

            var client = new HttpClient();
            var tweetTask = client.GetAsync(webUri);
            Task<JObject> jsonTask = tweetTask.Result.Content.ReadAsAsync<JObject>();
            var results = jsonTask.Result;

            model.AddRange((from b in results["results"]
                     select new Tweets()
                         {
                             Name = b["from_user"].ToString(),
                             Text = b["text"].ToString()
                         }).ToList());

            return View(model);
        }
    }
}

谢谢,但是我不能使用Deserialize,因为我收到的消息是“Newtonsoft.Json.JsonConvert'不包含'Deserialize'的定义”。我猜应该是DeserializeObject? - Dave
是的,DeserializeObject<T>()。就是这个。 - Raymond Saltrelli
Ray,你的一些代码没有起作用(尽管你给了我正确的答案),我已经更新了我的工作示例,希望这样可以。 - Dave
没问题。你的方法在风格上不是我会用的,但它完全有效。看起来你只需要从System.Json.JsonObject切换到Newtonsoft.Json.Linq.JObject,对吧? - Raymond Saltrelli
没错,但我不知道这个对象(或程序集)的存在,所以谢谢。 - Dave

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接