将字符串列表反序列化为JSON在Kotlin中

huangapple go评论93阅读模式
英文:

deserialize list of strings into JSON in kotlin

问题

I'm trying to deserialize the following string into JSON:

  1. {
  2. "user_id": "id1",
  3. "old_user_ids": ["id1", "id2", "id3"],
  4. "status": "ACTIVE"
  5. }

I tried to deserialize using:

  1. val record = objectMapper.readValue(myList, UserRecord::class.java)

My data class looks like this:

  1. data class UserRecord(
  2. var user_id: String = "",
  3. var old_user_ids: List<String> = emptyList(),
  4. var status: String = ""
  5. )

However, I'm getting the following error:

  1. Cannot construct instance of `java.util.ArrayList` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('[') at [Source: (String)...

I would appreciate if someone can point me to what I'm having wrong.

英文:

I'm trying to deserialize the following string into JSON

  1. val myList =&quot;&quot;&quot;{&quot;user_id&quot;: &quot;id1&quot; ,&quot;old_user_ids&quot;: &quot;[&quot;id1,id2,id3&quot;]&quot;, &quot;status&quot;:&quot;ACTIVE&quot;}&quot;&quot;&quot;

I tried to deserialize using

  1. val record = objectMapper.readValue(myList, UserRecord::class.java)

my data class looks like this

  1. data class UserRecord(
  2. var user_id: String = &quot;&quot;,
  3. var old_user_ids: List&lt;String&gt; = emptyList(),
  4. var status: String = &quot;&quot;
  5. )

however, I'm getting the following error

  1. Cannot construct instance of `java.util.ArrayList` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value (&#39;[&#39;) at [Source: (String)&quot;{&quot;user_id&quot;: &quot;id1&quot; ,&quot;old_user_ids&quot;: &quot;[&quot;id1,id2,id3&quot;]&quot;, &quot;status&quot;:&quot;ACTIVE&quot;}&quot;;

I would appreciate if someone can point me to what I'm having wrong.

Output I'm trying to get is

  1. {
  2. &quot;user_id&quot;: &quot;id1&quot;,
  3. &quot;old_user_ids&quot;: [&quot;id1&quot;,&quot;id2&quot;,&quot;id3&quot;],
  4. &quot;status&quot;:&quot;ACTIVE&quot;
  5. }

答案1

得分: 1

你的JSON格式不正确,应该是:

  1. {"user_id": "id1", "old_user_ids": ["id1", "id2", "id3"], "status": "ACTIVE"}

你在数组的 [] 分隔符周围使用了引号,这是导致问题的原因。此外,数组中的每个项都需要用引号括起来。

英文:

Your JSON is invalid, it should be

  1. {&quot;user_id&quot;: &quot;id1&quot; ,&quot;old_user_ids&quot;: [&quot;id1&quot;,&quot;id2&quot;,&quot;id3&quot;], &quot;status&quot;:&quot;ACTIVE&quot;}

You have quotes around the [ ] array delimiters which is why it's choking on that first character. Also your items in the array need quotes around each.

huangapple
  • 本文由 发表于 2023年6月8日 00:33:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76425417.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定