About Me

My photo
Talk to me... you will know

Tuesday, February 07, 2012

Escape Sequencer


To access json strings which have been returned with a double quote often poses a problem on the server side as the characters are not in sync with the values and cannot be processed... So the following problem will help you process the same problem by escaping the character in the json data daved in a file.


//buzz.txt



{"groupOp":"AND","rules":[{"field":"tlc_product_number","op":"eq","data":"2563"},{"field":"tlc_product_desc","op":"eq","data":"1" SPECIAL LABEL (CATERING)"},{"field":"fobsdate","op":"eq","data":"02/01/2012"}]




// EscapeSequencer.java




package com.string.regex;


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;






public class EscapeSequencer {
public static void main(String args[]){
List<Integer> ind1= new ArrayList<Integer>();
List<Integer> ind2= new ArrayList<Integer>();
String val= "";
try {
val= readFileAsString("C:/buzz");
System.out.println(val);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int pro=val.indexOf("data\":\"")+6;
String word1 = "data\":\"";
String word2 = "\"}";
String value="";
String filterVal=val.substring(pro,val.indexOf('"', pro));
for(int i=0;i<val.length();i++)
{
if(i+word1.length()<=val.length()){

String compString = val.substring(i, i+word1.length());
if(compString.equalsIgnoreCase(word1))
{


i=i+word1.length();
ind1.add(i);


}



}
//System.out.println(ind1.toString());


}
for(int i=0;i<val.length();i++)
{
if(i+word2.length()<=val.length()){
String compString= val.substring(i,i+word2.length());
if(compString.equalsIgnoreCase(word2))
{
i=i+word2.length();
ind2.add(i);
}
}
//System.out.println(ind2.toString());
}


System.out.println(val.indexOf("\"}"));
for(int j=0;j<ind1.size();j++){
try{
filterVal=val.substring(ind1.get(j)+1,ind2.get(j)-2);
//System.out.println(val.indexOf("\"}"));
}
catch(StringIndexOutOfBoundsException sie)
{
sie.printStackTrace();
}
value=filterVal;
//System.out.println(value+"...");
filterVal=filterVal.replace("\\", "\\\\")
   .replace("\"", "\\\"")
   .replace("\r", "\\r")
   .replace("\n", "\\n");
val=val.replace(value, filterVal);
System.out.println(val);
}


}
private static String readFileAsString(String filePath)
    throws java.io.IOException{
        StringBuffer fileData = new StringBuffer(1000);
        BufferedReader reader = new BufferedReader(
                new FileReader(filePath));
        char[] buf = new char[1024];
        int numRead=0;
        while((numRead=reader.read(buf)) != -1){
            String readData = String.valueOf(buf, 0, numRead);
            fileData.append(readData);
            buf = new char[1024];
        }
        reader.close();
        return fileData.toString();
    }
}

19 comments: