需求:
1 2 3 4 5 6 7 8 |
四个字符串: "[\"HDC-51\"]", "[\"HDC-51\", \"HDC-55\"]", "[\"HDC-50\", \"HDC-55\", \"HDC-55-2\"]", "[\"HDC-51\", \"HDC-55\", \"HDC-55-2\",\"HDC-21N\"]", 分别向四个字符串中添加String macType ="HDC-50" , 并判断字符串中各个元素是否与macType相同, 相同则不添加, 不相同则添加. 最后输出四个字符串,要求格式同开始字符串格式一致. |
思路:
1 2 |
这是不是普通的字符串, 而是json格式的字符串, 所以在判断的时候, 可以选择将多个字符串转成jsonArray格式 |
延伸:
1 2 |
通常我们在数据库中, 一个字段存储多个字符串的数据, 一般以json格式存入, 更新数据的时候,使用jsonArray转化更方便 |
方法一: 普通方式,不使用jsonArray
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
public class Test { public static void main(String[] args) {
List<String> contentList = new ArrayList<>(); contentList.add( "[\"HDC-51\"]" ); contentList.add( "[\"HDC-51\", \"HDC-55\"]" ); contentList.add( "[\"HDC-50\", \"HDC-55\", \"HDC-55-2\"]" ); contentList.add( "[\"HDC-51\", \"HDC-55\", \"HDC-55-2\",\"HDC-21N\"]" ); System.out.println(contentList); String macType = "HDC-50" ;
for (String content : contentList) {
//去掉content 中的中括号 String contentStr1 = content.replaceAll( "[\\[\\]]" , "" ); List<String> content1= Arrays.asList(contentStr1.split( "," ));
List<String> list = new ArrayList<>();
for (String string : content1) { list.add(string); }
//判断content中是否已经包含macType boolean flag = false ; for (String string : list) { //去掉字符串的引号 String str= string.replace( "\"" , "" ); if (macType.equals(str)) { flag = true ; break ; } }
//如果没有macType,则添加 if (flag == false ) { StringBuilder sb = new StringBuilder(); String macTypeStr = sb.append( "\"" ).append(macType).append( "\"" ).toString(); list.add(macTypeStr); }
String newContent = list.toString(); System.out.println(newContent);
} } } |
结果:
方法二: 使用JsonArray
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
public class Test { public static void main(String[] args) {
List<String> contentList = new ArrayList<>(); contentList.add( "[\"HDC-51\"]" ); contentList.add( "[\"HDC-51\", \"HDC-55\"]" ); contentList.add( "[\"HDC-50\", \"HDC-55\", \"HDC-55-2\"]" ); contentList.add( "[\"HDC-51\", \"HDC-55\", \"HDC-55-2\",\"HDC-21N\"]" ); System.out.println(contentList); String macType = "HDC-50" ;
for (String content : contentList) {
try { JSONArray contentArray = JSONArray.parseArray(content);
//System.out.println("contentArray前 : " + contentArray); if (!contentArray.contains(macType)) { contentArray.add(macType); } System.out.println( "contentArray后 : " + contentArray); } catch (Exception e) {
e.printStackTrace(); } } } }
|
控制台输出:
到此这篇关于Java之JsonArray用法讲解的文章就介绍到这了,更多相关Java之JsonArray用法内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
原文链接:https://blog.csdn.net/xinyuezitang/article/details/89213783
查看更多关于Java之JsonArray用法讲解的详细内容...