Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

In my application, I need to pass JSON array to java then convert that array to java array using java as a language. Here is the code.

JavaScript

  function arraytofile(rans)
  {
      myData.push(rans); // rans is the random number
      var arr = JSON.stringify(myData);// converting to json array
      android.arraytofile(arr); // passing to java
  }

Java

  public void arraytofile(String newData) throws JSONException {
      Log.d(TAG, "MainActivity.setData()");
      System.out.println(newData);
  }

newData is printing data as [[2],[3],[4]]... I want in regular java array. How I can achieve this?

share|improve this question
2  
Use a JSON parser library like Jackson or Gson. This is not hard to check on the net using your favorite SEO. –  Luiggi Mendoza May 8 at 7:09
    
json.org/java –  Mohammad Adil May 8 at 7:11
    
@MohammadAdil no, please no. Anything is better as a JSON library for Java than org.json. Please. –  fge May 8 at 7:12
    
@fge OMG.. is there anything wrong with that ? i personally use that in my project. –  Mohammad Adil May 8 at 7:15
    
How to implement? I am learning java. So takes time to understand –  user3335796 May 8 at 7:19

1 Answer 1

You can use Google gson . An excellent Java library to work with JSON.

Find it here: https://code.google.com/p/google-gson/

Using gson library classes you can do something like this:

    // I took a small sample of your sample json
    String json = "[[2],[3],[4]]";
    JsonElement je = new JsonParser().parse(json);
    JsonArray jsonArray = je.getAsJsonArray();
    // I'm assuming your values are in String, you can change this if not
    List<String> javaArray = new ArrayList<String>();
    for(JsonElement jsonElement : jsonArray) {
        JsonArray individualArray = jsonElement.getAsJsonArray();
        JsonElement value = individualArray.get(0);
        // Again, I'm assuming your values are in String
        javaArray.add(value.getAsString());
    }

Now you have your json as Java List<String>. That's basically as array.

If you know exact number of results, you can surely define an array of fix size and then assign values to it.

If you know Java, than you already know how to go from here.

I hope this helps.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.