我是Java的新手,但是对Java知道很多。我试图通过做一些小的项目来学习基础知识,以理解语言和代码。在Java中,我做了很多工作,将地图中的数据存储在json文件中,当您启动程序时,json文件会将数据加载到地图中。
Java示例:
public Map<Integer, Client> example = new HashMap<>();
这里是Client类:
public class Client {
private String username;
private String password;
private String host;
public Client(String username, String password, String host) {
this.username = username;
this.password = password;
this.host = host;
}
public String getPassword() {
return password;
}
public String getHost() {
return host;
}
public String getUsername() {
return username;
}
}
我想做同样的事情,但是现在使用Javascript。我的地图看起来像这样:
var price= new Map();
就像上面的Java示例一样,我想将这样的Map加载到json文件中,并希望将json文件中的数据加载到我的map中。
有人可以为我提供一个很好的代码示例,如何将json中的数据存储在我的地图中?甚至教程的链接也很棒!
答案 0 :(得分:2)
在JS中,使用普通对象而不是Map()
更为常见。
例如,假设您具有相同的Client
类:
class Client {
constructor(username, password, host) {
this.username = username;
this.password = password;
this.host = host;
}
}
const client1 = new Client('username1', 'password1', 'localhost');
const client2 = new Client('username2', 'password2', 'localhost');
您的价格映射(从int
到Client
)如下所示:
const price = {
1: client1,
2: client2
};
现在,您可以将其序列化为json:
const json = JSON.stringify(price);
或从json解析:
const price = JSON.parse(json);
但是,如果您真的想使用Map
,请使用tutorial。