Java - Create JSON Object from Multiple Multidimensional Arrays
I'm trying to convert a very complex array structure to a JSON object, but I'm not sure how to work with the conversion. The structure is as follows:
String[] foo = new String[10];
String[][] bar = new String[10][8];
String[][] blargh = new String[8][2];
// Populate foo
foo[0] = "foo1";
// ... and so on
bar[0][0] = "bar1";
// ... and so on
blargh[0][0] = "blargh1;"
// ... and so on
Then:
public JSONObject createJSONObject() {
/* Now, I would like to create an object with the structue:
[{
foo[0] : {
bar[0][0] : {
// more key-pair values, including blargh[0][0] and blargh[0][1]
},
bar[0][1] : {
// values of blargh[1][0] and blargh[1][1]
},
// etc...
},
foo[1] : {
bar[1][0] : {
开发者_运维问答 /* primary index of bar will always match index of foo, as will the primary index of blargh */
},
// etc..
},
// etc..
}]
// return the JSON encoded object
}
This seems reasonably complex to me, so please tell me if my question/code/structure is confusing or not clear.
Break it down into manageable chunks. Create methods that understand how to construct each nested object individually, and then call them at the appropriate times. For instance, something like:
public JSONObject createJSONObject() {
JSONObject result = new JSONObject();
for (int fooIndex = 0; fooIndex < foo.length; fooIndex++) {
result.put(foo[fooIndex], createBarJsonObject(fooIndex));
}
return result;
}
private JSONObject createBarJsonObject(int index) {
JSONObject result = new JSONObject();
String[] keys = bar[index];
for (int barIndex = 0; barIndex < keys.length; barIndex++) {
result.put(keys[barIndex], createBlarghJsonObject(fooIndex));
}
return result;
}
private JSONObject createBlarghJsonObject(int index) {
JSONObject result = new JSONObject();
String[] keyValue = blargh[index];
result.put(keyValue[0], keyValue[1]);
return result;
}
You're not creating arrays, you're creating objects. There's no point in the enclosing array in your pseudo code.
Object: { key0:val0, key1:val1 }
Array: [ val0, val1, val2 ]
{ // start object
key_foo0 : // foo[0] string as a key
{ // new object as a value
key_bar0_0 :
{
key_blargh0_0: val_blargh0_1, // blargh[0][1] as value
key_bleuuw0_0: val_bleuuw0_1
}
}
} // end object
精彩评论