Task: there is a string like
(zzzz (aaaa "bbbb1 bbbb2" (ccccc "dddd1 dddd2" (eeeee)) ffff (gggg hhhh) iiiii jjjj))
It is necessary to write a recursion program in Java, which translates such a list into an ArrayList
with multi-level nesting, i.e. the bracket in line is a recess to the level, the element of the arraylist itself becomes an arraylist, etc., for example, in this sample line on the top level there are two elements: zzzz and the arraylist of aaaa bbbb are still an arrey sheet from cccc dddd and so on .. .
Quoted strings should be taken as a single block, i.e. from quotes to quotes!
Please help me with the algorithm, otherwise my version does not work correctly ( Gson
not pay attention to Gson
):
import com.google.gson.Gson; import java.util.ArrayList; public class Parser { String inputString; String commandLine; public Parser(String in,String com){ this.inputString=in; this.commandLine=com; } public String parse() { Gson json = new Gson(); ArrayList result=getDevicesList(); return json.toJson(result); } private ArrayList getDevicesList() { ArrayList result=getBracketBlock(0,this.inputString); return result; } private ArrayList getBracketBlock(int pos, String in) { ArrayList buffer = new ArrayList(); String token = ""; Boolean IS_STRING = false; String source = in.substring(pos); char [] chr = source.toCharArray(); pos=0; while( chr[pos]!=')') { if( chr[pos]=='(' ) { buffer.add(getBracketBlock(pos+1,source.substring(pos))); } if( chr[pos]==' ' && !token.equals("")) { if(!IS_STRING) { buffer.add(token);System.out.println(token+" "+pos); token=""; } } if(chr[pos]=='\"') IS_STRING=!IS_STRING; token+=chr[pos]; pos++; } buffer.add(token); return buffer; } }