Java 将字符串反序列化为对象
将此字符串格式转换为对象的最佳方式是什么Java 将字符串反序列化为对象,java,Java,将此字符串格式转换为对象的最佳方式是什么 [Start successful - User:Berord; Name:Test; Fruits:Orange; Version:;] 我想用“;”分开和do子字符串(str.indexOf(“用户:”)+1),子字符串(str.indexOf(“名称:”)+1) 还有其他更好的方法吗?拆分;首先,您将得到一个大小为3的字符串数组,您可以将其循环并拆分为: String s = "Start successful - User:Berord; N
[Start successful - User:Berord; Name:Test; Fruits:Orange; Version:;]
我想用“;”分开和do子字符串(str.indexOf(“用户:”)+1),子字符串(str.indexOf(“名称:”)+1)
还有其他更好的方法吗?拆分;首先,您将得到一个大小为3的字符串数组,您可以将其循环并拆分为:
String s = "Start successful - User:Berord; Name:Test; Fruits:Orange; Version:;".replace("Start successful -","");
String splits[]=s.split(";");
for(String split:splits)
{
String splittedStrings[] =split.split(":");
String key = splittedStrings[0];
String value = splittedStrings[1];
}
分裂;首先,您将得到一个大小为3的字符串数组,您可以将其循环并拆分为:
String s = "Start successful - User:Berord; Name:Test; Fruits:Orange; Version:;".replace("Start successful -","");
String splits[]=s.split(";");
for(String split:splits)
{
String splittedStrings[] =split.split(":");
String key = splittedStrings[0];
String value = splittedStrings[1];
}
如果用户数据总是以字段名withoutspaces:DataWithOutSemicolon的形式出现;您可以将以下正则表达式与模式和匹配器一起使用:(\S+):([^;]*);并从每个匹配中提取第1组和第2组 例如:
Pattern p = Pattern.compile("(\\S+):([^;]*);");
Matcher m= p.matcher( "[Start successful - User:Berord; Name:Test; Fruits:Orange; Version:;]" );
while( m.find() ) {
String key = m.group( 1 );
String value = m.group( 2 );
//put those into a map or use in some other way, for demonstration I'll print them
System.out.println( key + "::" + value );
}
这将导致以下输出
User::Berord
Name::Test
Fruits::Orange
Version::
请注意,该键不应包含空格,但至少应在其前面加一个空格,否则您将匹配更多的空格,即,如果您的输入是[启动成功用户:Berord;名称:Test;水果:Orange;版本:;]
您将得到key=“成功用户:Berord;名称:Test;水果”
和value=“Orange”
。同样,您的值不应该包含分号,否则匹配也会被弄乱
如果您要求空格必须是可选的,并且值可能包含分号,那么正则表达式可能会变得更复杂(取决于要求),甚至根本不适合使用,在这种情况下,您需要使用(write)一个更专业的解析器。如果用户数据总是以FieldNameWithoutSpaces的形式出现:DataWithOutSemicolon;您可以将以下正则表达式与模式和匹配器一起使用:(\S+):([^;]*);并从每个匹配中提取第1组和第2组 例如:
Pattern p = Pattern.compile("(\\S+):([^;]*);");
Matcher m= p.matcher( "[Start successful - User:Berord; Name:Test; Fruits:Orange; Version:;]" );
while( m.find() ) {
String key = m.group( 1 );
String value = m.group( 2 );
//put those into a map or use in some other way, for demonstration I'll print them
System.out.println( key + "::" + value );
}
这将导致以下输出
User::Berord
Name::Test
Fruits::Orange
Version::
请注意,该键不应包含空格,但至少应在其前面加一个空格,否则您将匹配更多的空格,即,如果您的输入是[启动成功用户:Berord;名称:Test;水果:Orange;版本:;]
您将得到key=“成功用户:Berord;名称:Test;水果”
和value=“Orange”
。同样,您的值不应该包含分号,否则匹配也会被弄乱
如果您要求空格必须是可选的,并且值可能包含分号,则正则表达式可能会变得更复杂(取决于要求),甚至根本不适合使用-在这种情况下,您需要使用(编写)一个更专业的解析器。我将一步一步地拆分此
字符串
:
-
)分割输入,以便仅访问感兴趣的部分;
)拆分这个有趣的部分以获得键值对:
)拆分每个键值对,以分别获取键和值映射来存储键值对。
下面的代码中进行了一些优化,例如trim()
以消除键和值中的前导空格和尾随空格,一些(可能已过时)检查映射中是否存在键,以及一些检查拆分操作的结果
下面是一个示例解决方案,请阅读注释:
public static void main(String args[]) {
String s = "Start successful - User:Berord; Name:Test; Fruits:Orange; Version:;";
// provide a data structure that holds the desired key-value pairs
Map<String, String> kvMap = new HashMap<>();
// (#1) split the input by minus ('-') to get rid of the leading part
String[] splitByMinus = s.split("-");
// check if the result length is the expected one
if (splitByMinus.length == 2) {
// (#2) take the desired part and split it again, this time by semicolon (';')
String[] splitBySemicolon = splitByMinus[1].split(";");
for (String ss : splitBySemicolon) {
// (#3) split the result of the splitting by semicolon another time, this time
// by a colon (':')
String[] splitByColon = ss.split(":");
// again, check the length of the result
if (splitByColon.length == 2) {
// if yes, you have successfully extracted the key and value, erase leading and
// trailing spaces
String key = splitByColon[0].trim();
String value = splitByColon[1].trim();
// check if the map contains the key
if (kvMap.containsKey(key)) {
// YOU DECIDE: skip this entry or update the existing key with the new value
System.out.println("There already is a key " + key + ". What now?");
} else {
// if the map doesn't have the key, insert it along with the value
kvMap.put(key, value);
}
} else if (splitByColon.length == 1) {
System.out.println(
"There was a key or value missing the corresponding key or value: \""
+ splitByColon[0].trim()
+ "\" (splitting by colon resulted in only one String!)");
// for the moment, we regard this case as a key without a value
String key = splitByColon[0].trim();
// check if the map contains the key
if (kvMap.containsKey(key)) {
// YOU DECIDE: skip this entry or update the existing key with the new value
System.out.println("There already is a key " + key
+ ". What now? This time there is no new value, "
+ "so skipping this entry seems a good idea.");
// do nothing...
} else {
// if the map doesn't have the key, insert it along with the value
kvMap.put(key, null);
}
} else {
System.err.println("Splitting by colon resulted in an unexpected amount of Strings,"
+ "here " + splitByColon.length);
}
}
} else {
System.err.println("Splitting the input String resulted in an unexpected amount of parts");
}
// finally print your results that are stored in the map:
kvMap.forEach((key, value) -> System.out.println(key + " : " + (value == null ? "" : value)));
}
publicstaticvoidmain(字符串参数[]){
String s=“启动成功-用户:Berord;名称:Test;水果:橙色;版本:;”;
//提供保存所需键值对的数据结构
Map kvMap=newhashmap();
//(#1)将输入除以减号('-')以除去前导部分
字符串[]splitby减号=s.split(“-”);
//检查结果长度是否为预期长度
if(SplitBy减号.length==2){
//(#2)取所需的部分并再次拆分,这次用分号(“;”)
字符串[]splitBySemicolon=SplitBy减号[1]。拆分(;);
for(字符串ss:splitBySemicolon){
//(#3)再次使用分号拆分拆分结果,这次是
//通过冒号(“:”)
字符串[]splitByColon=ss.split(“:”);
//再次检查结果的长度
if(splitByColon.length==2){
//如果是,则表示已成功提取键和值,请删除前导和
//尾随空间
String key=splitByColon[0]。trim();
字符串值=splitByColon[1]。trim();
//检查地图是否包含密钥
if(kvMap.containsKey(键)){
//您可以决定:跳过此项或使用新值更新现有键
System.out.println(“已经有一个键“+key+”。现在怎么办?”);
}否则{
//如果贴图没有键,请将其与值一起插入
kvMap.put(键、值);
}
}else if(splitByColon.length==1){
System.out.println(
“有一个键或值缺少相应的键或值:\”
+splitByColon[0].trim()
+“\”(冒号分隔只产生一个字符串!);
//目前,我们认为这个案例是一个没有价值的关键
String key=splitByColon[0]。trim();
//检查地图是否包含密钥
if(kvMap.containsKey(键)){
//您可以决定:跳过此项或使用新值更新现有键
System.out.println(“已经有一个键”+键
+“.现在怎么办?这次没有新的价值,”
+“所以跳过这个条目似乎是个好主意。”);
//什么也不做。。。
}否则{
//如果贴图没有键,请将其与值一起插入
kvMap.put(key,null);
}
}否则{