本文介绍了使用GSON创建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有关的问题是将@添加到某些字段的开头。我尝试使用注释,但是我收到错误:
java.lang.IllegalArgumentException:@context不是有效的JSON字段名称。
没有SerializedName注解中的@,它可以正常工作。似乎Gson无法处理@,即使它是有效的JSON?解析方案
我认为问题在于 Gson版,它至少可以使用1年。
所以请使用
最新版本,
,它应该可以正常工作。 p>
以下是您可以执行的一些奇怪的事情:
静态类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;
}
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?
解决方案
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;
}
这篇关于使用GSON创建JSON-LD的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!