package cn
.alan
;
import com
.alibaba
.fastjson
.JSON
;
import com
.alibaba
.fastjson
.JSONArray
;
import com
.alibaba
.fastjson
.JSONObject
;
public class Main {
public static void main(String
[] args
) {
String jsonStr
="{'userName':'root','password':'123456'}";
User javaObject
=JSON
.parseObject(jsonStr
, User
.class);
System
.out
.println(javaObject
.getUserName());
System
.out
.println(javaObject
.getPassword());
User user
=new User("user","user123");
String userJson
=JSON
.toJSONString(user
);
System
.out
.println(userJson
);
String jsonStr3
= "[{\"password\":\"123\",\"userName\":\"张三\"},{\"password\":\"321\", \"userName\":\"李四\"}]";
JSONArray jsonArray
=JSON
.parseArray(jsonStr3
);
for (int i
= 0; i
< jsonArray
.size(); i
++) {
JSONObject object
=jsonArray
.getJSONObject(i
);
String userName
=object
.getString("userName");
String password
=object
.getString("password");
System
.out
.println(userName
+"---"+password
);
}
String json4
="{'userName':'json4','password':'123'}";
JSONObject jsonObject4
=JSONObject
.parseObject(json4
);
User user4
= JSONObject
.toJavaObject(jsonObject4
, User
.class);
System
.out
.println(user4
.getUserName()+"---"+user4
.getPassword());
}
}
package cn
.alan
;
public class User {
private String userName
;
private String password
;
public User() {
}
public User(String userName
, String password
) {
this.userName
= userName
;
this.password
= password
;
}
public String
getUserName() {
return userName
;
}
public void setUserName(String userName
) {
this.userName
= userName
;
}
public String
getPassword() {
return password
;
}
public void setPassword(String password
) {
this.password
= password
;
}
@Override
public String
toString() {
return "User{" +
"userName='" + userName
+ '\'' +
", password='" + password
+ '\'' +
'}';
}
}
转载请注明原文地址:https://tech.qufami.com/read-20951.html