我有一个枚举:
enum Type {
LIVE, UPCOMING, REPLAY
}
Run Code Online (Sandbox Code Playgroud)
还有一些JSON:
{
"type": "live"
}
Run Code Online (Sandbox Code Playgroud)
一节课:
class Event {
Type type;
}
Run Code Online (Sandbox Code Playgroud)
当我尝试反序列化JSON的,使用GSON,我收到null的Event类型字段,因为在JSON类型字段的情况下,不匹配的枚举.
Events events = new Gson().fromJson(json, Event.class);
Run Code Online (Sandbox Code Playgroud)
如果我将枚举更改为以下,那么一切正常:
enum Type {
live, upcoming, replay
}
Run Code Online (Sandbox Code Playgroud)
但是,我想将枚举常量保留为全部大写.
我假设我需要编写一个适配器,但没有找到任何好的文档或示例.
什么是最好的解决方案?
编辑:
我能够让JsonDeserializer工作.有没有更通用的方法来编写这个,因为每次枚举值和JSON字符串之间的情况不匹配时都必须编写它.
protected static class TypeCaseInsensitiveEnumAdapter implements JsonDeserializer<Type> {
@Override
public Type deserialize(JsonElement json, java.lang.reflect.Type classOfT, JsonDeserializationContext context)
throws JsonParseException {
return Type.valueOf(json.getAsString().toUpperCase());
}
}
Run Code Online (Sandbox Code Playgroud) 试图在Kotlin中解析JSON数组,使它适用于单个JSON对象到WeatherObject对象(下面的代码片段)
{
"coord": {
"lon": -2.93,
"lat": 43.26
},
"weather": [{
"id": 802,
"main": "Clouds",
"description": "scattered clouds",
"icon": "03d"
}],
"main": {
"temp": 283.681,
"temp_min": 283.681,
"temp_max": 283.681,
"pressure": 991.72,
"sea_level": 1034.92,
"grnd_leve": 991.72,
"humidity": 98
},
"wind": {
"speed": 1.07,
"deg": 144.001
},
"dt": 1429773245,
"id": 3128026,
"name": "Bilbao",
"cod": 200
Run Code Online (Sandbox Code Playgroud)
}
但如果JSON是一个具有相同JSON对象的数组,即不确定如何做同样的事情
从json数组[{},{} ...]到ArrayList <WeatherObject>
就像是:
fun getWeatherObjectArrayFromJson(jsonStr: String): ArrayList<WeatherObject >
Run Code Online (Sandbox Code Playgroud)
有问题的gsonBuilder.registerTypeAdapter(ArrayList <WeatherObject> :: class.java,WeatherDeserializer())
class WeatherObject {
var main: String = ""
var description: String = …Run Code Online (Sandbox Code Playgroud) 我有这样的课程
class Holder {
public int ObjType { get; set; }
public List<Base> Objects { get; set; }
}
abstract class Base {
// ... doesn't matter
}
class DerivedType1 : Base {
// ... doesn't matter
}
class DerivedType2 : Base {
// ... doesn't matter
}
Run Code Online (Sandbox Code Playgroud)
使用WebAPI我想要接收对象Holder并正确反序列化它.基于ObjType值,我需要Objects将要反序列化的属性作为List<DerivedType1>(ObjType == 1)或List<DerivedType2>(ObjType == 2).
目前我搜索了SO和互联网以获得最佳方法,但我找到的最好的是这个答案/sf/answers/562189841/.这个解决方案的问题是,它松散了父对象的上下文,所以我找不到它的值ObjType.OK,我可以创建自定义解决它JsonConverter用于Holder和remebering的ObjType价值,但我还是很affraid这行
serializer.Populate(jObject.CreateReader(), target); …Run Code Online (Sandbox Code Playgroud) 我遇到了棘手的问题.
我有一个这种格式的JSON字符串:
[{
"record":
{
"Name": "Komal",
"Age": 24,
"Location": "Siliguri"
}
},
{
"record":
{
"Name": "Koena",
"Age": 27,
"Location": "Barasat"
}
},
{
"record":
{
"Name": "Kanan",
"Age": 35,
"Location": "Uttarpara"
}
}
... ...
]
Run Code Online (Sandbox Code Playgroud)
"记录"中的字段可以增加或减少.
所以,我做了这样的课程:
public class Person
{
public string Name;
public string Age;
}
public class PersonList
{
public Person record;
}
Run Code Online (Sandbox Code Playgroud)
并试图像这样反序列化:
JavaScriptSerializer ser = new JavaScriptSerializer();
var r = ser.Deserialize<PersonList>(jsonData);
Run Code Online (Sandbox Code Playgroud)
我做错了什么.但无法找到.你能帮忙吗?
提前致谢.
更新:
实际上我收到错误"无效的JSON原语:." 由于我正在使用此代码读取文件的字符串:
public static bool ReadFromFile(string path, string …Run Code Online (Sandbox Code Playgroud) 我有一个用C#定义的枚举,我将它的值存储为字符,如下所示:
public enum CardType
{
Artist = 'A',
Contemporary = 'C',
Historical = 'H',
Musician = 'M',
Sports = 'S',
Writer = 'W'
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试使用JSON.NET反序列化,但传入的JSON是使用CHAR值(字符串)而不是枚举的int值编写的,如下所示:
[{"CardType","A"},{"CardType", "C"}]
Run Code Online (Sandbox Code Playgroud)
是否可以定义某种转换器,允许我手动将char解析为枚举值?
我尝试创建一个JsonConverter,但不知道该怎么做,同时只将它应用于此属性而不是整个解析对象.这是我试过的:
public class EnumerationConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, value);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
return null;
}
int value = serializer.Deserialize<int>(reader);
return (CardType)value;
}
public override bool CanConvert(Type objectType) …Run Code Online (Sandbox Code Playgroud) Swift JSONDecoder提供了一个dateDecodingStrategy属性,允许我们根据DateFormatter对象定义如何解释传入的日期字符串.
但是,我目前正在使用一个API,它返回date strings(yyyy-MM-dd)和datetime strings(yyyy-MM-dd HH:mm:ss),具体取决于属性.有没有办法JSONDecoder处理这个,因为提供的DateFormatter对象一次只能处理dateFormat一个?
一个火腿解决方案是重写附带的Decodable模型,只接受字符串作为其属性,并提供公共Dategetter/setter变量,但这对我来说似乎是一个糟糕的解决方案.有什么想法吗?
我有这个 API
public ActionResult AddDocument([FromBody]AddDocumentRequestModel documentRequestModel)
{
AddDocumentStatus documentState = _documentService.AddDocument(documentRequestModel, DocumentType.OutgoingPosShipment);
if (documentState.IsSuccess)
return Ok();
return BadRequest();
}
Run Code Online (Sandbox Code Playgroud)
这是我的请求模型
public class AddDocumentRequestModel
{
public AddDocumentRequestModel(int partnerId, List<ProductRequestModel> products)
{
PartnerId = partnerId;
Products = products;
}
[Range(1, int.MaxValue, ErrorMessage = "Value for {0} must be between {1} and {2}.")]
public int PartnerId { get; private set; }
[Required, MustHaveOneElement(ErrorMessage = "At least one product is required")]
public List<ProductRequestModel> Products { get; private set; }
}
Run Code Online (Sandbox Code Playgroud)
所以当我试图用这个身体点击 API 时
{ …Run Code Online (Sandbox Code Playgroud) 我尝试反序列化包含null属性的对象并具有JsonMappingException.
我所做的:
String actual = "{\"@class\" : \"PersonResponse\"," +
" \"id\" : \"PersonResponse\"," +
" \"result\" : \"Ok\"," +
" \"message\" : \"Send new person object to the client\"," +
" \"person\" : {" +
" \"id\" : 51," +
" \"firstName\" : null}}";
ObjectMapper mapper = new ObjectMapper();
mapper.readValue(new StringReader(json), PersonResponse.class); //EXCEPTION!
Run Code Online (Sandbox Code Playgroud)
但是:如果扔掉"firstName = null"财产 - 一切正常!我的意思是传递下一个字符串:
String test = "{\"@class\" : \"PersonResponse\"," +
" \"id\" : \"PersonResponse\"," +
" \"result\" : \"Ok\"," + …Run Code Online (Sandbox Code Playgroud) 我试图弄清楚如何使用Serde将JSON反序列化为结构.例如,serde_json 自己的文档中的示例JSON 包含以下数据:
{
"FirstName": "John",
"LastName": "Doe",
"Age": 43,
"Address": {
"Street": "Downing Street 10",
"City": "London",
"Country": "Great Britain"
},
"PhoneNumbers": [
"+44 1234567",
"+44 2345678"
]
}
Run Code Online (Sandbox Code Playgroud)
现在,如果我们假设上面的数据是在变量"input"和下面的代码中:
let deserialized_data: Data = serde_json::from_str(input).unwrap();
Run Code Online (Sandbox Code Playgroud)
......结构应该是什么Data样的?
我正在使用 .Net Core 3.0 并有以下字符串,我需要用 Newtonsoft.Json 反序列化:
{
"userId": null,
"accessToken": null,
"refreshToken": null,
"sessionId": null,
"cookieExpireTimeSpan": {
"ticks": 0,
"days": 0,
"hours": 0,
"milliseconds": 0,
"minutes": 0,
"seconds": 0,
"totalDays": 0,
"totalHours": 0,
"totalMilliseconds": 0,
"totalMinutes": 0,
"totalSeconds": 0
},
"claims": null,
"success": false,
"errors": [
{
"code": "Forbidden",
"description": "Invalid username unknown!"
}
]
}
Run Code Online (Sandbox Code Playgroud)
并遇到以下错误:
Newtonsoft.Json.JsonSerializationException : Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.TimeSpan' because the type requires a JSON primitive value (e.g. …Run Code Online (Sandbox Code Playgroud) timespan json.net json-deserialization .net-core .net-core-3.0