标签: json-deserialization

GSON非区分大小写的Enum反序列化

我有一个枚举:

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,我收到nullEvent类型字段,因为在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)

java gson json-deserialization

28
推荐指数
4
解决办法
1万
查看次数

在Kotlin中使用Gson来解析JSON数组

试图在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&lt;WeatherObject &gt
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)

android gson kotlin json-deserialization

26
推荐指数
1
解决办法
2万
查看次数

JSON.NET:如何根据父(持有者)对象值反序列化接口属性?

我有这样的课程

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)

c# json.net asp.net-web-api json-deserialization

23
推荐指数
1
解决办法
1万
查看次数

在C#中反序列化JSON数组

我遇到了棘手的问题.

我有一个这种格式的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# json deserialization json-deserialization

22
推荐指数
2
解决办法
11万
查看次数

将json字符反序列化为枚举

我有一个用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)

c# json enumeration json.net json-deserialization

21
推荐指数
2
解决办法
2万
查看次数

Swift的JSONDecoder在JSON字符串中有多种日期格式?

Swift JSONDecoder提供了一个dateDecodingStrategy属性,允许我们根据DateFormatter对象定义如何解释传入的日期字符串.

但是,我目前正在使用一个API,它返回date strings(yyyy-MM-dd)和datetime strings(yyyy-MM-dd HH:mm:ss),具体取决于属性.有没有办法JSONDecoder处理这个,因为提供的DateFormatter对象一次只能处理dateFormat一个?

一个火腿解决方案是重写附带的Decodable模型,只接受字符串作为其属性,并提供公共Dategetter/setter变量,但这对我来说似乎是一个糟糕的解决方案.有什么想法吗?

json-deserialization swift codable

21
推荐指数
5
解决办法
7545
查看次数

不支持没有无参数构造函数的引用类型的反序列化

我有这个 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)

serialization json-deserialization .net-core-3.0

21
推荐指数
3
解决办法
2万
查看次数

JSON:JsonMappingException同时尝试使用空值反序列化对象

我尝试反序列化包含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)

java json jackson json-deserialization

20
推荐指数
2
解决办法
7万
查看次数

Rust&Serde JSON反序列化示例?

我试图弄清楚如何使用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样的?

json rust json-deserialization serde

16
推荐指数
1
解决办法
6050
查看次数

.Net Core 3.0 TimeSpan 反序列化错误 - 在 .Net 5.0 中修复

我正在使用 .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

16
推荐指数
2
解决办法
1万
查看次数