0

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?

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

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

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.