项目要求实现用户注册,登陆,修改密码和注销等功能。这里把每个用户的用户名和密码保存成键值对的形式,利用JSON模块进行操作
1.实体结构可以根据自己的JOSN结构去构建
package com.job.xx;
import java.io.Serializable;
import java.util.List;
public class FeatureTypes implements Serializable {
private List<FeatureType> featureType;
public List<FeatureType> getFeatureType() {
return featureType;
}
public void setFeatureType(List<FeatureType> featureType) {
this.featureType = featureType;
}
@Override
public String toString() {
return "FeatureTypes{" +
"featureType=" + featureType +
'}';
}
}
class FeatureType implements Serializable {
private String name;
private String href;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHref() {
return href;
}
public void setHref(String href) {
this.href = href;
}
@Override
public String toString() {
return "FeatureType{" +
"name='" + name + '\'' +
", href='" + href + '\'' +
'}';
}
}
2.转换成实体对象。JOSNObject的getObject()方法,可以把json数据转换成对象数据。
JSONObject jsonObject = JSONObject.parseObject(json);
FeatureTypes featureTypes = jsonObject.getObject("featureTypes", FeatureTypes.class);
import json
# 用户信息字典
user_info = {}
# 保存用户信息到文件
def save_info():
with open('user_info.json', 'w') as f:
json.dump(user_info, f)
# 从文件加载用户信息
def load_info():
global user_info
with open('user_info.json', 'r') as f:
user_info = json.load(f)
# 注册用户
def register(username, password):
if username in user_info:
print('用户名已存在!')
else:
user_info[username] = password
print('注册成功!')
save_info()
# 登录
def login(username, password):
if username not in user_info or user_info[username] != password:
print('用户名或密码错误!')
else:
print('登录成功!')
# 修改密码
def change_password(username, new_password):
if username not in user_info:
print('用户名不存在!')
else:
user_info[username] = new_password
print('密码修改成功!')
save_info()
# 注销用户
def logout(username):
if username not in user_info:
print('用户名不存在!')
else:
user_info.pop(username)
print('注销成功!')
save_info()
# 加载用户信息
load_info()
while True:
cmd = input('请输入注册(r)、登录(l)、修改密码(c)或注销(d):')
if cmd == 'r':
username = input('请输入用户名:')
password = input('请输入密码:')
register(username, password)
elif cmd == 'l':
username = input('请输入用户名:')
password = input('请输入密码:')
login(username, password)
elif cmd == 'c':
username = input('请输入用户名:')
new_password = input('请输入新密码:')
change_password(username, new_password)
elif cmd == 'd':
username = input('请输入用户名:')
logout(username)
else:
print('不存在的命令!')