Creating JSON-LD using GSON

眉间皱痕 提交于 2020-02-04 04:56:08

问题


I'm trying to read/write JSON-LD documents using Gson. An example of JSON-LD:

{
  "@context": {
    "name": "http://xmlns.com/foaf/0.1/name",
    "homepage": {
      "@id": "http://xmlns.com/foaf/0.1/workplaceHomepage",
      "@type": "@id"
    },
    "Person": "http://xmlns.com/foaf/0.1/Person"
  },
  "@id": "http://me.markus-lanthaler.com",
  "@type": "Person",
  "name": "Markus Lanthaler",
  "homepage": "http://www.tugraz.at/"
}

The problem I have with Gson is adding the @ to the beginning of some of the fields. I tried using the @SerializedName annotation but I get errors:

java.lang.IllegalArgumentException: @context is not a valid JSON field name.

Without the "@" in the SerializedName annotation it works fine. Seems that Gson cannot handle the "@" even though it is valid JSON?


回答1:


I think the issue is your Gson version, it works at least for 1 year.

So please use the latest version, 2.2.4 from May, and it should just work.

Here is an example of strange things you can do:

static class A
{
    @SerializedName("@co.nte:xt|")
    public String s;
}

public static void main(String[] args) throws Exception
{       
    Gson gson = new Gson();
    A a = gson.fromJson("{ \"@co.nte:xt|\": \"s\"}", A.class);      
    return;
}


来源:https://stackoverflow.com/questions/17188543/creating-json-ld-using-gson

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!