Java中有类似JSON的对象吗?

Java中有类似JSON的对象吗?,java,Java,在C#中,您可以 var cat=new {amount=4,sound="mouw",food="fish"}; 那你呢 print("My cat ate "+cat.food+" "+cat.amount+"es"); 然后它会打印出来 My cat ate 4 fishes 有没有像Java这样酷的东西?我想你要找的是对象。你可以自己定义它们,比如 class Cat { int amount; String sound; String food;

在C#中,您可以

var cat=new {amount=4,sound="mouw",food="fish"};
那你呢

print("My cat ate "+cat.food+" "+cat.amount+"es");
然后它会打印出来

My cat ate 4 fishes

有没有像Java这样酷的东西?

我想你要找的是对象。你可以自己定义它们,比如

class Cat {
    int amount;
    String sound;
    String food;

    Cat(int amount, String sound, String food) {
       this.amount = amount;
       this.sound = sound;
       this.food = food;
    }
}
然后上一堂主课

public class Main {
    public static void main(String[] args) {
        Cat cat = new Cat(4, "mouw", "fish");
        System.out.println("My cat ate " + cat.amount + " " + cat.amount + "es");
    }
}
以下是一个很好的资源,可以帮助您开始:

    • 将介绍该语言,但我们在Java9中还没有实现。因为您使用的是var关键字,所以我还想参考一下关于局部变量类型推断的内容。这些在Java中都不可用


      也许我误解了你的问题,而你只是在寻找普通的旧Java对象,那么的答案将帮助你解决问题。

      它并不真正像JSON对象,但在Java中,你可以使用枚举或类来做你想做的事情。例如,做如下事情:

      public enum Cat{
          String food = "fish"; 
          String amount = "5";
       }
      
      然后就像你的例子:

      System.out.println("My cat ate "+Cat.food+" "+Cat.amount+"es");
      

      或者你可以使用一个类,做一些类似的事情来完成同样的事情(这可能是一个更好的主意)。

      谢谢你回答我的问题。为每个人定义一个命名类很麻烦。如果一个方法中需要使用100个对象,那么为每个对象定义一个类并不是最好的主意,尽管它是可行的(无论是否在bean模式中)。我想Java缺乏这种能力。使用您给出的动物示例,我将研究抽象类:它将有助于减少您需要编写的代码量。这可能是一种非常接近的方法。Java没有var类型,因此可能无法实现。