简体   繁体   中英

pass a javascript array to java array using json

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"));
        }
    }

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

}
 JSON.stringify(array)

没有你的代码很难看到你想要的东西,但这就是你如何将js数组转换为JSON obj

你可以使用J SON Serialize方法传递j子串...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM