有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用GSON读取以数字作为名称的JSON变量

首先,我是GSON的初学者,所以请容忍我

我尝试从此url读取JSON:

https://gdata.youtube.com/feeds/api/videos?author=radityadika&v=2&alt=jsonc

我成功地读取了一个字符串变量,如“id”、“data”、“uploader”等

但是,如何读取content(在items内)?我想获取RTSP链接(content:1),但我的Java代码一直给我错误,因为我无法用数字命名变量,如:

String 1 = "asd";

非常感谢您的帮助,谢谢您的帮助


共 (4) 个答案

  1. # 1 楼答案

    首先需要定义几个类:

    MyGson

    public class MyGson {
    private String apiVersion;
    private Data data;
    
    public Data getData() {
        return data;
    }
    }
    

    数据

    public class Data {
    private String updated;
    private int totalItems = 0;
    private int startIndex = 0;
    private int itemsPerPage = 0;
    private  List<Item> items;
    
    public List<Item> getItems() {
        return items;
    }
    }
    

    项目

     public class Item {
    private String id;
    private String uploaded;
    private String updated;
    private String uploader;
    private String category;
    private String title;
    private String description;
    private Map<Integer, String>  content;
    
    public Map<Integer, String> getContent() {
        return content;
    }
    }
    

    看看,你的content是地图,其中key是1,2,3,4,5,6

    您可以定义Map<String, String> content,但由于所有键都是整数

    现在,您可以提取任何想要的值:

    启动器

     ....
     Gson gson = new Gson();
    
        MyGson myGson = gson.fromJson(str, MyGson.class);
    
        List<Item> items = myGson.getData().getItems();
    
        if(items.size()>0){
            Item item = items.get(0);
    
            String myStr = item.getContent().get(1);
    
            System.out.println(myStr);
        }
    

    输出:

    rtsp://r6---sn-cg07lue6.c.youtube.com/CiILENy73wIaGQl1cubZZSUSXxMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp
    
  2. # 2 楼答案

    虽然很旧,但也许有人还需要它

    要序列化名为Integer的属性,只需将模型类设置为:

    Json:

    {
      "name": "foo",
      "1": "value one",
      "2": "value two",
      "3": "value three"
    }
    

    爪哇:

    import com.google.gson.annotations.SerializedName;
    
    public class Foo {
    
       private String name;
    
       @SerializedName("1")
       private String one;
    
       @SerializedName("2")
       private String two;
    
       @SerializedName("3")
       private String three;
    
       // standard getter & setters bellow...
    
    }
    
  3. # 3 楼答案

    Java语言不允许这样的变量命名

    此处引用了相关例外,详情请参见下面的链接, http://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html

    Every programming language has its own set of rules and conventions for the kinds of names that you're allowed to use, and the Java programming language is no different. The rules and conventions for naming your variables can be summarized as follows:

    1. Variable names are case-sensitive. A variable's name can be any legal identifier — an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign "$", or the underscore character "". The convention, however, is to always begin your variable names with a letter, not "$" or "". Additionally, the dollar sign character, by convention, is never used at all. You may find some situations where auto-generated names will contain the dollar sign, but your variable names should always avoid using it. A similar convention exists for the underscore character; while it's technically legal to begin your variable's name with "_", this practice is discouraged. White space is not permitted.

    2. Subsequent characters may be letters, digits, dollar signs, or underscore characters. Conventions (and common sense) apply to this rule as well. When choosing a name for your variables, use full words instead of cryptic abbreviations. Doing so will make your code easier to read and understand. In many cases it will also make your code self-documenting; fields named cadence, speed, and gear, for example, are much more intuitive than abbreviated versions, such as s, c, and g. Also keep in mind that the name you choose must not be a keyword or reserved word.

    3. If the name you choose consists of only one word, spell that word in all lowercase letters. If it consists of more than one word, capitalize the first letter of each subsequent word. The names gearRatio and currentGear are prime examples of this convention. If your variable stores a constant value, such as static final int NUM_GEARS = 6, the convention changes slightly, capitalizing every letter and separating subsequent words with the underscore character. By convention, the underscore character is never used elsewhere.

  4. # 4 楼答案

    考虑到contentJSON对象如下所示:

    "content": {
        "1": "someLink",
        "5": "someOtherLink",
        ...
    }
    

    解析该JSON对象的最佳方法是将其作为Map(请参见Map documentation),因此只需向Item类添加一个属性,如下所示:

    private Map<Integer, String> content;
    

    基本上,映射是一个包含key - value对的对象,在本例中,键是Integer,值是String

    因此,您可以访问您的链接,查找要检索的值的键,对于第一个链接,它只是:

    String someLink = content.get(new Integer(1));
    

    请注意,这样做可以为链接提供不同的编号。现在你有1,5和6。但你可以有任何整数和任意数量的链接