我无法获得JSON和Java对象一起工作的要点。基本上我需要做的是检查一个URL的JSON文件,看看是否有更新版本的软件可供使用。我打开了连接,并可以将JSON打印到控制台,但这就是我运气好的一切。我一直在尝试使用GSON。下面是我迄今为止的主要代码,其中清单是类的对象,显示在更下面。我最关心的是JSON中的“版本”字段,因为我需要将它与我当前的程序版本号进行比较。在URL中寻找JSON文件中的某些字段
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
stringV = reader.readLine();
//System.out.println(manifest);
while ((line = reader.readLine()) != null) {
stringV = stringV + gson.toJson(line);
//manifest = manifest + line;
}
System.out.println(manifest);
manifest man = gson.fromJson(manifest, manifest.class);
testString = man.getversion();
System.out.println(test);
我的一个问题涉及到我专用于JSON类,我需要有声明,获取/套,所有在JSON中的字段?
public class manifest{
private List<String> versions;
private String version;
private String current;
private String compatible;
private String published;
private String description;
private List<String> manifest;
private String jre;
public List<String> getVersions(){return versions;}
public String getversion(){return version;}
public String getcurrent(){return current;}
public String getcomp(){return compatible;}
public String getpub(){return published;}
public String getdesc(){return description;}
public List<String> getFileList(){return manifest;}
public String getjre(){return jre;}
public void setVersions(List<String> versions){this.versions = versions;}
public void setversion(String version){this.version = version;}
public void setcurrent(String current){this.current = current;}
public void setcomp(String compatible){this.compatible = compatible;}
public void setpub(String published){this.published = published;}
public void setdesc(String description){this.description = description;}
public void setFileList(List<String> manifest){this.manifest = manifest;}
public void setjre(String jre){this.jre = jre;}
@Override
public String toString(){
return String.format("Versions:%s,version:%s,curr:%s,comp:%s,pub:%s,desc:%s,manifest:%s,jre:%s",
versions, version, current, compatible, published, description, manifest, jre);
}
}
这里的JSON的结构:
{
"versions": [
{
"version": "II V7.1.2",
"current": true,
"compatible": true,
"published": "2012-04-21T18:25:43-05:00",
"description": "Stability improvements for users:\n\n-Fix a crash\n-Fix a bug",
"manifest": [
{
"name": "file.jar",
"checksum": "56116165156111156156116161651161616116165116116516651651"
}, (more elements here)
"jre": "1.7.0_17"
任何帮助是非常赞赏,因为我不熟悉JSON的。谢谢!
非常感谢!现在它更有意义。 – 2013-03-19 18:13:45
之后,为了从JSON对象获取特定的信息字段,你会推荐使用解析器吗?还是有更简单的方法? – 2013-03-19 18:18:08
将其转换为Java对象后,您不需要执行任何其他解析,只需访问与其他对象相同的对象属性即可。 – Perception 2013-03-19 18:42:02