【发布时间】:2022-07-19 22:37:55
【问题描述】:
我尝试将 json(来自 API)解析为我的对象。
JSON 看起来像这样
[
{
"bookId": 1,
"title": "Test Book 1",
"description": "Test Book 1 Description",
"coverImageUrl": "https://via.placeholder.com/150",
"layout": "FullScreen",
"categories": [
1,
2
],
"tags": [
1,
2
]
},
{
"bookId": 2,
"title": "Test Book 2",
"description": "Test Book 2 Description.",
"coverImageUrl": "https://via.placeholder.com/150",
"layout": "FullScreen",
"categories": [
1
],
"tags": []
}
]
我使用 JSON Helper 类:
public class JsonHelper
{
public static T[] getJsonArray<T>(string json)
{
string newJson = "{ \"array\": " + json + "}";
Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>(newJson);
return wrapper.array;
}
[System.Serializable]
private class Wrapper<T>
{
public T[] array;
}
}
为了反序列化它,我使用:
BookDTO[] books;
books = JsonHelper.getJsonArray<BookDTO>(jsonData)
Books DTO 对象如下所示: 使用 System.Collections.Generic;
namespace API.DTOs
{
[System.Serializable]
public class BookDTO : DTO
{
public int bookId { get; set; }
public string title { get; set; }
public string description { get; set; }
public string coverImageUrl { get; set; }
public string layout { get; set; }
public ICollection<int> categories { get; set; }
public ICollection<int> tags { get; set; }
public BookDTO(int bookId, string title, string description, string coverImageUrl, string layout, ICollection<int> categories, ICollection<int> tags)
{
this.bookId = bookId;
this.title = title;
this.description = description;
this.coverImageUrl = coverImageUrl;
this.layout = layout;
this.categories = categories;
this.tags = tags;
}
}
}
我还尝试了以下方法,因为类别和标签也是数组:
using System.Collections.Generic;
namespace API.DTOs
{
[System.Serializable]
public class BookDTO : DTO
{
public int bookId { get; set; }
public string title { get; set; }
public string description { get; set; }
public string coverImageUrl { get; set; }
public string layout { get; set; }
public Categories[] categories { get; set; }
public Tags[] tags { get; set; }
public BookDTO(int bookId, string title, string description, string coverImageUrl, string layout, ICollection<int> categories, ICollection<int> tags)
{
this.bookId = bookId;
this.title = title;
this.description = description;
this.coverImageUrl = coverImageUrl;
this.layout = layout;
string newCategories = "{ \"cat\": " + categories + "}";
this.categories = JsonHelper.getJsonArray<Categories>(newCategories);
string newTags = "{ \"tag\": " + tags + "}";
this.tags = JsonHelper.getJsonArray<Tags>(newTags);
}
}
[System.Serializable]
public class Categories
{
public int[] cat;
}
[System.Serializable]
public class Tags
{
public int[] tag;
}
}
但我总是得到一个包含两本书的 Books 数组,并且所有值都为空。
【问题讨论】:
-
为什么要在 json 文本中添加“数组”?如果添加它,您是在 DTO 基础中捕获它吗?
-
一个用于创建 JSON 模型的好工具是 app.quicktype.io
-
作为一般规则,除非它相当简单,否则我会推荐 Newtonsoft Json 而不是 JsonUtility,因为它有点限制。
-
@Mernayi 我添加数组,因为这篇文章:answers.unity.com/questions/1290561/… 我认为统一将通过参数名称映射它
-
@pixlhero 你太棒了,先生。与 Newtonsoft Json 完美配合
标签: c# arrays json unity3d serialization