我无法将 JSON 和 Java 对象的要点一起工作。基本上我需要做的是检查 URL 上的 JSON 文件,看看是否有可用的更新版本的软件。我已经打开了连接,可以将 JSON 打印到控制台,但这就是我所拥有的一切。我一直在尝试主要使用 GSON。下面是我到目前为止的主要代码,清单是下面显示的类的对象。我最关心的是 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。谢谢!