2013-06-19 92 views
2

我正在尝试使用Gson读取/写入JSON-LD文档。 JSON-LD的一个例子:使用GSON创建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/" 
} 

我与Gson有关的问题是将@添加到某些字段的开头。我尝试使用@SerializedName注解,但是我得到的错误:

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

没有在SerializedName注释正常工作的“@”。似乎Gson不能处理“@”,即使它是有效的JSON?

+0

哪个GSON的版本您使用的? – Pragmateek

回答

3

我认为问题是您的Gson版本,它至少工作1年。

所以请使用最新版本2.2.4五月,它应该只是工作。

这里是你可以做的奇怪的事情为例:

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; 
}