0

I'm trying to pass a javascript array of items to a java server using JSON. my server receives the following String:

[
    {"attr1":"SomeValue1","attr2":"SomeValue2"},
    {"attr1":"SomeValue3","attr2":"SomeValue4"}
]

I'm trying to use JsonArray, but am probably doing it wrong (I'm not adding my code here since it is probably just stupid).

Can anyone give me the proper way of creating an iterating over the values from my String?

Edit: as requested, my stupid code:

    jsnobject = new JSONObject(items);  //items is the string described above
    JSONArray jsonArray = jsnobject.getJSONArray("");
    if(jsonArray != null){
        for(int i=0 ; i<jsonArray.length();i++){
            JSONObject explrObject = jsonArray.getJSONObject(i);
            System.out.println("name = "+explrObject.get("fileName"));
        }
    }
4
  • 4
    I'm not adding my code here since it is probably just stupid we learn from making stupid things and convert them into awesome. Post your code and we will help you on the process. Commented Apr 30, 2014 at 16:03
  • You have to post your code here, however stupid you think it might appear, otherwise your question is likely to be closed. Commented Apr 30, 2014 at 16:03
  • What JSON library do you use? Certainly the JSONObject and JSONArray classes must come from somewhere. Commented Apr 30, 2014 at 16:17
  • @T-Bull json.org Commented Apr 30, 2014 at 16:19

3 Answers 3

2

I've never used JsonArray(previously I've used gson to go between json and Java), but looking at the documentation

It looks like you can create the JsonArray by passing in a correct json string into the constuctor. Then you should be able to iterate through it like a typical array.

JsonArray myArray = new JsonArray(jsonString);
int length = myArray.length();
for(int i=0; i<length; i++){
     myArray.get(i) 
//note this returns an object of type object, 
//use other get functions to get other types

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

3 Comments

Tried that, recived an error that a JSON string must start with a '{'
That is the answer, have no idea why it didnt work the first time - thanks
@user1432310 Be sure to use a JSON validation tool when running into problems. Javascript/JSON is painful without the proper tools.
0
 JSON.stringify(array)

without your code it is hard to see what you are wanting but this is how you convert js array to a JSON obj

1 Comment

The problem seems to be in Java side, not in JavaScript side.
0

You can use J SON Serialize method you can pass the j son string ...

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.