模拟实现一个解析JSON字符串为JAVA对象的函数,要求入参为String字符串,返回为List,其中Alert的成员变量为id,app,ip,类型均为String型。不可使用现成的开源解析工具
提示:Java面试题
文章目录
前言
这里我解析json字符串是使用正则表达式来完成
一、正则表达式
使用正则表达式分解字符串,使用以下方法来解析
//将给定的正则表达式编译为模式。参数:regex–要编译的表达式
public static Pattern compile(String regex)
//创建一个匹配器,该匹配器将根据此模式匹配给定的输入。参数:input–要匹配的字符序列
public Matcher matcher(CharSequence input)
//Matcher类,如果且仅当输入序列的子序列与匹配器的模式匹配,则为true
public boolean find()
二、完整代码如下
1.主要代码
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/*
模拟实现一个解析JSON字符串为JAVA对象的函数,要求入参为String字符串,返回为List<Alert>,其中Alert的成员变量为id,app,ip,类型均为String型。不可使用现成的开源解析工具
*/
public class StringToJson {
public static List<Alert> StringToJson(String jsonStr){
//正则表达式,要匹配的模式"{.*}",'{'的unicode字符为\u007B
Pattern pattern = Pattern.compile("\\u007B.*?}");
//输入要匹配的字符
Matcher matcher = pattern.matcher(jsonStr);
int i =0;
List<Alert> list = new ArrayList<>();
while (matcher.find()){
//用map来接收解析字符
Map<String, String> map = new HashMap<>();
//把'{'和'}'替换掉
String group = matcher.group().toString().replace("{","").replace("}","");
//根据','来分割
String[] split1 = group.split(",");
Alert alert = new Alert();
//根据','遍历
for (String s : split1){
//根据':'分割
String[] split2 = s.split(":");
//map接收数据
map.put(split2[0].toString().replace("\"",""),split2[1].toString().replace("\"",""));
}
alert.setId(map.get("id"));
alert.setApp(map.get("app"));
alert.setIp(map.get("ip"));
list.add(alert);
}
System.out.println(list);
return list;
}
public static void main(String[] args) {
String json = "[{\"id\":\"3\",\"app\":\"F-AMC\",\"ip\":\"1.1.1.1\"},{\"id\":\"2\",\"app\":\"F-OSCM\",\"ip\":\"2.2.2.2\"},{\"id\":\"1\",\"app\":\"F-PCAP\",\"ip\":\"3.3.3.3\"}]";
StringToJson(json);
}
}
2.Alert类
public class Alert {
private String id;
private String app;
private String ip;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getApp() {
return app;
}
public void setApp(String app) {
this.app = app;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
@Override
public String toString() {
return "Alert{" +
"id='" + id + '\'' +
", app='" + app + '\'' +
", ip='" + ip + '\'' +
'}';
}
}
总结
以上就是我解析json字符串的方法,这里仅仅简单介绍了Pattern类和Matcher类的使用。