31
List<User> list = LoadUsers();

JObject json = new JObject();

json["users"] = new JValue(list);

Doesn't seem to be working?

Error:

Could not determine JSON object type for type System.Collections.Generic.List`1

My under development local drupal site become very slow, how to solve?

I am developing locally a site with drupal and suddenly it became very slow. The last thing I made was installing the internationalization module.

Now when I try to reach administration panel I receive:

Fatal error: Maximum execution time of 60 seconds exceeded...

What to do now? Should I increase the maximum execution time allowed? OR could be that I have too many modules installed?

EDIT: Forgot to tell you that I am working on a PC with 2GB RAM and CPU 2.9 GHz, Windows XP + XAMPP

4

2 回答 2

63

AJValue只能包含简单的值,如字符串、整数、布尔值、日期等。它不能包含复杂的对象。我怀疑你真正想要的是:

List<User> list = LoadUsers();

JObject json = new JObject();

json["users"] = JToken.FromObject(list);

以上将User对象列表转换为代表用户的 a of,然后将其分配给JArraynew上的属性。您可以通过检查 的属性来确认这一点,看看它是 。JObjectsusersJObjectTypejson["users"]Array

相反,如果您json["users"] = new JValue(JsonConvert.SerializeObject(list))按照此问题的另一个答案(现已删除)中的建议进行操作,您可能不会得到您正在寻找的结果。这种方法会将用户列表序列化为一个字符串,从中创建一个简单的,JValue然后将 分配JValueusers. JObject如果您检查 的Type属性json["users"],您会发现它是String。这意味着,如果您稍后尝试使用 将 转换JObject为 JSON json.ToString(),您将获得双序列化输出,而不是您可能期望的 JSON。

这是一个简短的演示来说明差异:

class Program
{
    static void Main(string[] args)
    {
        List<User> list = new List<User>
        {
            new User { Id = 1, Username = "john.smith" },
            new User { Id = 5, Username = "steve.martin" }
        };

        JObject json = new JObject();

        json["users"] = JToken.FromObject(list);
        Console.WriteLine("First approach (" + json["users"].Type + "):");
        Console.WriteLine();
        Console.WriteLine(json.ToString(Formatting.Indented));

        Console.WriteLine();
        Console.WriteLine(new string('-', 30));
        Console.WriteLine();

        json["users"] = new JValue(JsonConvert.SerializeObject(list));
        Console.WriteLine("Second approach (" + json["users"].Type + "):");
        Console.WriteLine();
        Console.WriteLine(json.ToString(Formatting.Indented));
    }

    class User
    {
        public int Id { get; set; }
        public string Username { get; set; }
    }
}

输出:

First approach (Array):

{
  "users": [
    {
      "Id": 1,
      "Username": "john.smith"
    },
    {
      "Id": 5,
      "Username": "steve.martin"
    }
  ]
}

------------------------------

Second approach (String):

{
  "users": "[{\"Id\":1,\"Username\":\"john.smith\"},{\"Id\":5,\"Username\":\"steve.martin\"}]"
}
于 2013-12-25T06:15:07.053 回答
6

我遇到了这个问题,如果您只想要没有根名称的数组项,您现在可以使用 JArray 来完成此操作。

var json = JArray.FromObject(LoadUsers());

如果您希望 json 数组的根名称为“用户”,您可以使用

var json = new JObject { ["users"] = JToken.FromObject(LoadUsers()) };
于 2018-01-04T17:27:55.433 回答