0

The below code gives result as test:[someproduct, someproduct, someproduct, someproduct, someproduct]. I am expecting result as ["someproduct", "someproduct", "someproduct", "someproduct", "someproduct"] so that I will push the string array into json response

String[] Id = new String[5];
for (int i = 0; i < 5; i++) {
    Id[i] ="someproduct";
}
System.out.println("test:"+Arrays.toString(Id));
writer.key("product").value(Arrays.toString(Id));

When I try access the jsonresponse like response.product[0], i am getting first character '[' alone. I suppose to get first item(someproduct) of the array.

Please help me to resolve.

4
  • 5
    If Arrays.toString(Id) doesn't produce the output you desire, simply loop over the array and build that output yourself. Commented May 21, 2015 at 12:30
  • It's unclear what writer is, but does writer.key("product").value(Id); give the output you seek? Commented May 21, 2015 at 12:32
  • sorry, i am expecting result as ["someproduct", "someproduct", "someproduct", "someproduct", "someproduct"] so that I can call res[0], res[1] etc. Can anyone help me write regular expression on this? Commented May 21, 2015 at 13:14
  • You expect that result when you print it out to screen? How do you print it? Commented May 22, 2015 at 5:09

6 Answers 6

2

the problem is the method you are using is not sufficient. one way of doing this, is to use another type of array (e.g. ArrayList) then Override its toString method.

here is an example:

 public static void main(String... args) throws Exception{
    ArrayList<String> array=new ArrayList<String>(){

        /**
         * 
         */
        private static final long serialVersionUID = 1L;

        @Override
        public String toString(){
            StringBuilder sb = new StringBuilder();
            sb.append("[");
            boolean isFirst=true;
            for(String s : this){
                if(!isFirst){
                    sb.append(",");
                }
                isFirst=false;
                sb.append("\""+s+"\"");
            }
            sb.append("]");
            return sb.toString();
        }
    };


    for (int i = 0; i < 5; i++) {
      array.add("someproduct");
    }
    System.out.println(array);


}

output:

["someproduct","someproduct","someproduct","someproduct","someproduct"]

NOTE:

There are many ways to make this code reusable, e.g.

  1. creating a new class ArrayListWithNicePrint that extends ArrayList
  2. creating a static method that returns you a fresh ArrayList with nice Print (I prefer this one really)

EDIT: (Based ON comment):

public class ArrayListWithNicePrint<E> extends ArrayList{


        @Override
        public String toString(){
            StringBuilder sb = new StringBuilder();
            sb.append("[");
            boolean isFirst=true;
            for(Object s : this){
                if(!isFirst){
                    sb.append(",");
                }
                isFirst=false;
                sb.append("\""+s.toString()+"\"");
            }
            sb.append("]");
            return sb.toString();
        }

    }

Testing:

public class Testing{
   public static void main(String... args){

   ArrayListWithNicePrint<String> list= new ArrayListWithNicePrint<String>();
   list.add("hi");
   list.add("hello");
   System.out.println(list);
   }
}
Sign up to request clarification or add additional context in comments.

5 Comments

thanks, we can do it by overriding toString method !
As you ve suggested to create new class ArrayListWithNicePrint that extends ArrayList. can you please give me some example for the this.
thanks for your response Nafas. I have tried above the code, have added public static void main but it returns me "[someproduct, someproduct, someproduct, someproduct, someproduct]" without having double quotes. It seems toString() method is not called. Am I missing anything?
@ezhil I think you made a mistake on the initializations. I've added a test class and made the ArrayListWithNicePrint public to make it easier accessible.
thanks Nafas, it is working fine.there was some problem while initialization. once again thanks a lot :)
1

Try this :

String[] Id = new String[5];

for(int i = 0; i < 5; i++) 
 {

   Id[i] =" **\"someproduct\"** ";

 }

hope it will work

1 Comment

Id[i] =" \"someproduct\" ";
1

You can use some JSON converter library, or as a quickfix you could use something like this:

String[] Id = new String[5];
for (int i = 0; i < 5; i++) {
    Id[i] ="\"someproduct\"";
}
String arrOutput = Arrays.toString(Id).replaceAll("\\[", "{").replaceAll("\\]", "}");
System.out.println("test:"+ arrOutput);
writer.key("product").value(arrOutput);

Depending on the content on your array elements more workaround would be needed. Maybe if you write more information we can help you better.

Comments

1

why dont u try putting it into a List and then use Gson to convert the whole list into json format, dig a bit to get the correct format of json u want. for retrieving u can retrieve easily with the tag names associated with each element. What u require is not very clear so this is the best guess i can make

Comments

1

Try with this code. it will resolve your issue.

    String[] Id = new String[5];
        for (int i = 0; i < 5; i++) {
            Id[i] ="\"someproduct\"";
        }
        System.out.println("test:"+Arrays.toString(Id).replace('[', '{').replace(']', '}'));

2 Comments

Is similar to my answer. OP wants that the elements are inside quotes ", as well.
Hi, i am expecting result as ["someproduct", "someproduct", "someproduct", "someproduct", "someproduct"]. how do we write regular express for this? pls help
0

When usin the JSONWriter object, you should use the built in array() and endArray() methods like this:

writer.key("product").array();
for (int i=0; i<5; i++) {
  writer.object();
  writer.key("name").value("someproductname" + i);
  writer.endObject();
}
writer.endArray();

http://www.json.org/javadoc/org/json/JSONWriter.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.