I want to convert "id=1&location=india" querystring to {"id":"1","location":"india"} json format using java.
I am using spring version 4.0.3.
Well this is not a direct way, but this is the first though came to my mind.
Convert the queryString to Hashtable using HttpUtils , then marshall it into JSON.
https://tomcat.apache.org/tomcat-7.0-doc/servletapi/javax/servlet/http/HttpUtils.html
Update:
HttpUtils produces Hashtable.
I think you can write a converter like this
public class ConvertToJson {
public static void main(String[] args) {
String a = "id=1&location=india";
System.out.println(convert(a));
}
private static String convert(String a) {
String res = "{\"";
for (int i = 0; i < a.length(); i++) {
if (a.charAt(i) == '=') {
res += "\"" + ":" + "\"";
} else if (a.charAt(i) == '&') {
res += "\"" + "," + "\"";
} else {
res += a.charAt(i);
}
}
res += "\"" + "}";
return res;
}
}
it can do the job for you
try this..
try
{
String query="id=1&location=india";
String queryArray[]=query.split("&");
String id[]=queryArray[0].split("=");
String location[]=queryArray[1].split("=");
JSONObject jsonObject=new JSONObject();
jsonObject.put(id[0],id[1]);
jsonObject.put(location[0],location[1]);
Log.i("Stackoverflow",jsonObject.toString());
}
catch (JSONException e)
{
e.printStackTrace();
Log.i("Stackoverflow",e.getMessage());
}
Related
I have two jsonobject which is in list. If I make new jsonobject and trying to get list in that it is giving me null.
Code is here below-
private int isExisting(String pid, List profile, String size) throws JSONException {
for (int i = 0; i < profile.size(); i++) {
JSONObject obj = new JSONObject(profile.get(i));
log.info("--------------" + obj.toString()); //it is giving me an empty object but list contains two objects {"size":"M","id":11} and {"size":8,"id":19}
}
}
I tried this it worked
private void isExisting(String pid, List profile, String size) throws JSONException {
for (int i = 0; i < profile.size(); i++) {
if(profile.get(i)!=null) {
JSONObject obj = new JSONObject(profile.get(i).toString());
System.out.print("keys----------" + obj.toString());
}
}
}
public void processList() {
try {
JSONObject objA= new JSONObject("{\n" +
" \"size\": \"M\",\n" +
" \"id\": 11\n" +
" }");
JSONObject objB=new JSONObject("{\n" +
" \"size\": 8,\n" +
" \"id\": 19\n" +
" }");
List<JSONObject> list=new ArrayList<>();
list.add(objA);
list.add(objB);
isExisting("",list,"");
} catch (JSONException e) {
e.printStackTrace();
}
}
I have tried this simple logic and it is working fine-
private int isExisting(String pid, List profile, String size) throws JSONException {
for (int i = 0; i < profile.size(); i++) {
JSONObject obj = (JSONObject) profile.get(i);
log.info("--------------" + obj.toString());
}
}
I am getting result in the form {a=2 ,b=5} after spel expression evaluation.
I want to convert it to json.
How do I do it?
Please help!
here is your solution:
public static void main(String[] args) {
String something = "{a=2 ,b=5}";
something = something.replace("{", "");
something = something.replace("}", "");
String[] pairs = something.split(",");
ArrayList<String> list = new ArrayList<String>();
for (String pair : pairs) {
list.add(pair);
}
for (int i = 0; i < list.size(); i++) {
String[] temp = list.get(i).split("=");
temp[0] = "\"" + temp[0] + "\"";
list.set(i, temp[0] + ":" + temp[1]);
}
String contents = "";
for (int i = 0; i < list.size(); i++) {
contents = contents + ", " + list.get(i);
}
contents = contents.replaceFirst(", ", "");
contents = "{" + contents + "}";
System.out.println("Contents: " + contents);
}
And here is your result:
Contents: {"a":2 , "b":5}
I'm trying to replace a value in the Value tag in an OMElement.
My code is only adding to it (the 564.12 value below it).
<b:UI022002D>
<b:Description>Box 2a (Taxable Amount)</b:Description>
<b:UIRef>UI022002D</b:UIRef>
<b:Value>564.1200</b:Value>
564.12
</b:UI022002D>
Code:
ArrayList
<OMElement>
aElem=getChildrenByPath(oForm, xpathNonUniueTag);
for(int i=0;i <aElem.size();i++) {
OMElement elem=aElem.get(i);
if (xpathNonUniueTag=="*/AmountFields/FormAmountField") {
if (sValue.length()> 2){
elem.setText(getChildText(elem, "Value").substring(0, sValue.length() - 2));
}
}
}
Found my answer:
private void mapNonUniqueNodes(OMElement oForm, String sFormID, String xpathNonUniueTag, String xpathChildNodeWithUniqueTag,
String sDescTag)
{
ArrayList<OMElement> aElem=getChildrenByPath(oForm, xpathNonUniueTag);
for(int i=0;i<aElem.size();i++)
{
OMElement elem=aElem.get(i);
String newTagName=getChildText(elem, xpathChildNodeWithUniqueTag);
newTagName=newTagName.replace("-", "");
String sDescTagValue=getChildText(elem, sDescTag);
if (xpathNonUniueTag == "*/AmountFields/FormAmountField") {
ArrayList<OMElement> aElem2=getChildrenByPath(elem, "*/Value");
log.info("aElem2 " + aElem2);
for(int e=0;e<aElem2.size();e++)
{
OMElement elem2=aElem2.get(e);
String sValue = elem2.getText();
if (sValue.length() > 2){
sValue = sValue.substring(0, sValue.length() - 2);
elem2.setText(sValue);
log.info("elem2 " + elem2);
log.info("elem2 text " + elem2.getText());
}
}
}
}
I get the HTML Javascript string such as :
htmlString = "https\x3a\x2f\x2ftest.com"
But I want to decode it as below :
str = "https://test.com"
That means , I want a Util API like :
public static String decodeHex(String htmlString){
// do decode and converter here
}
public static void main(String ...args){
String htmlString = "https\x3a\x2f\x2ftest.com";
String str = decodeHex(htmlString);
// str should be "https://test.com"
}
Does anybody know how to implement this API - decodeHex ?
This should be enough to get you started. I leave implementing hexDecode and sorting out malformed input as an exercise for you.
public String decode(String encoded) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < encoded.length(); i++) {
if (encoded.charAt(i) == '\' && (i + 3) < encoded.length() && encoded.charAt(i + 1) == 'x') {
sb.append(hexDecode(encoded.substring(i + 2, i + 4)));
i += 3;
} else {
sb.append(encoded.charAt(i));
}
}
return sb.toString;
}
public String decode(String encoded) throws DecoderException {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < encoded.length(); i++) {
if (encoded.charAt(i) == '\\' && (i + 3) < encoded.length() && encoded.charAt(i + 1) == 'x') {
sb.append(new String(Hex.decodeHex(encoded.substring(i + 2, i + 4).toCharArray()),StandardCharsets.UTF_8));
i += 3;
} else {
sb.append(encoded.charAt(i));
}
}
return sb.toString();
}
I am doing project using Lucen library in here I need to build query dynamically using Json object. so in here I use jettison library. as an example my json like this
{"OR":{"OR": {"fildKey1": "value1","fildKey2": "value2","fildKeyabc": "valueabc"},"AND": {"AND": {"fildKey3": "value3","OR": {"fildKey4": "value4","fildKey5": "value5"}},"fildKeyw": "valuew"}}}
using above json I need to create following query
(( fildKey1 : value1 OR fildKey2 : value2 OR fildKeyabc : valueabc )OR(( fildKey3 : value3 AND( fildKey4 : value4 OR fildKey5 : value5 ))AND fildKeyw : valuew ))
but I can't get the above query.my result is like this
(( fildKey1 : value1 OR fildKey2 : value2 OR fildKeyabc : valueabc )OR(( fildKey3 : value3 AND( fildKey4 : value4 OR fildKey5 : value5 )AND)AND fildKeyw : valuew )OR)
I need to remove above extra 2 operators this is my code
public class JettisionCls {
static Stack s = new Stack();
String operater = null;
static String res = "";
int bracket_counter = 0;
public void getKeyAndValue(JSONObject json_obj) throws JSONException{
Iterator<String> iter = json_obj.keys();
while (iter.hasNext()) {
String obj = iter.next();
if(obj.toLowerCase().equals("and") || obj.toLowerCase().equals("or")){
//System.out.print(obj);
operater = obj;
}
JSONObject temp = null;
try {
temp = new JSONObject(json_obj.get(obj).toString());
} catch (JSONException e) {
e.getStackTrace();
}
if (temp != null) {
//System.out.print("(");
res = res +"(";
bracket_counter=bracket_counter+1;
s.push(operater);
getKeyAndValue(temp);
//System.out.print(")");
res = res +")";
bracket_counter=bracket_counter-1;
if((s.size()) != 0 && bracket_counter != 0){
//System.out.print(s.peek());
s.pop();
res = res +s.peek();
}
else{
s.pop();
}
}
else{
if(iter.hasNext()){
res = res+" "+obj + " : " + json_obj.get(obj) + " " + operater; }
else{
res = res+" "+obj + " : " + json_obj.get(obj)+" ";
}
}
}
}
my main method look like this
String multiLevelQuery = "{\"OR\":{\"OR\": {\"fildKey1\": \"value1\",\"fildKey2\": \"value2\",\"fildKeyabc\": \"valueabc\"},\"AND\": {\"AND\": {\"fildKey3\": \"value3\",\"OR\": {\"fildKey4\": \"value4\",\"fildKey5\": \"value5\"}},\"fildKeyw\": \"valuew\"}}}";
JSONObject jobj = new JSONObject(multiLevelQuery);
JettisionCls obj = new JettisionCls();
obj.getKeyAndValue(jobj);
System.out.println(JettisionCls.res);
if anyone can please help me.
I think you can do this using string replacement.
public void createQry(String s){
String temp = s;
if(temp.contains(")OR)")){
temp = temp.replace(")OR)", "))");
}
if(s.contains(")AND)")){
temp = temp.replace(")AND)", "))");
}
System.out.println(temp);
}
Hmm, this is an interesting problem. But instead of brute force, I would have gone with something more elegant like recursion. The pushing, popping and concatinating will be done by recursion for you. In your code, I can see a lot of places where it can break. Even if you fix this issue, there is a chance that it will fail for another condition.
A sample algorithm with recursion would be
public String generateQuery(JSONObject json_obj) {
if(single_json_obj)
return generated_query_for_single_condition;
//else complex json with inner children
else
return generateQuery(innerJSONObject)
}
}