问题
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