create a JSON object from a string array in java - java

I have an array of strings like [1234_acb,2345_xyz]
I want to form a key value pair JSON Object like [{"1234":"abc"},{"2345":"xyz"}]
I have used split function to separate out the values from underscore

assume your string data is stored in data:
String keyValArray[] = data.split("_");
JSONArray jsonArray = new JSONArray();
for(int a=0;a<keyValArray.length-1;a+=2){
jsonArray.put(new JSONObject().put(keyValArray[a], keyValArray[a+1]));
}//for loop
String jsonStr = jsonArray.toString();
P.S: for loop limit is keyValArray.length-1 so keyValArray[a+1] does not go out of the array bound
P.S2: #njzk2 a++ changed to a+=2, to skip the value item in array, so it's not used as a key in the json object

Related

How to put data to parsed JSONObject

i have some parse code and to parsed JSONObject i need to add one more JSONObject, but getting error Unexpected token LEFT BRACE({), because my code creating multiply JSONObjects in file, not at parsed JSONObjec. Here is a code, that creating object
aJson = (JSONObject) parser.parse(reader);
JSONObject json = new JSONObject();
JSONArray blockData = new JSONArray();
for(Block b : blocks){
json.put("player-name", p.getName());
json.put("uuid", p.getUniqueId().toString());
json.put("nearestPlayers", new JSONArray());
blockData.add(b.getLocation().getWorld().getName());
blockData.add(b.getLocation().getWorld().getEnvironment());
blockData.add(b.getLocation().getX());
blockData.add(b.getLocation().getY());
blockData.add(b.getLocation().getZ());
}
aJson.put(blockData, json);
Here is JSON
{"[\"world\",NORMAL,-23.0,67.0,75.0]":{"player-name":"MisterFunny01","nearestPlayers":[],"uuid":"206d32da-bf72-3cfd-9a26-e374dd76da31"}} //here is that part// {"[\"world\",NORMAL,-23.0,67.0,75.0]":{"player-name":"MisterFunny01","nearestPlayers":[],"uuid":"206d32da-bf72-3cfd-9a26-e374dd76da31"},"[\"world\",NORMAL,-23.0,67.0,75.0]":{"player-name":"MisterFunny01","nearestPlayers":[],"uuid":"206d32da-bf72-3cfd-9a26-e374dd76da31"}}
In JSON array values must be of type string, number, object, array, boolean or null. Arrays hold values of the same type and not different types.
Looking at your code the array is an array of objects. So you would have to create an object and add the values before adding to the array.
Don't directly add values to the array but create an object and then add to the array.
Your code is wrong. To put an object into JSONObject please read this document
In your case, you need to convert blockData to String to put in the JSONObject.
It's like this: aJson.put(blockData as String, json);
Hope it can be helpful to you.

How to get a certain elements inside an array inside a jsonObject

I'm exporting some data in java using JSON then I'm reading that data and trying to get elements from an array inside the JSON object but I'm having issues.
I have tried a lot of things like
jsonObject.get("InGameCord").get("x")
Object Testo = jsonObject.get("InGameCord");
Testo.x
Things like that along with more that did not work so deleted the code.
This is the exported JSON file and im trying to access the InGameCord array X or Y.
{"BaseID":1,"BaseName":"Bandar-e-Jask Airbase","InGameCord":[{"x":463,"y":451}]}
Here is my file reader code
FileReader reader = new FileReader(filename);
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
System.out.println(jsonObject);
System.out.println("BaseName: "+jsonObject.get("BaseName"));
System.out.println("BaseID: "+jsonObject.get("BaseID"));
System.out.println("InGameCord: "+jsonObject.get("InGameCord"));
All of this works and exports the correct info.
So I'm trying to get let us say the X value of InGameCord.
int X = 463;
Given your JSON data {"BaseID":1,"BaseName":"Bandar-e-Jask Airbase","InGameCord":[{"x":463,"y":451}]}:
"InGameCord" is the name of an array which can be instantiated as a JSONArray.
That array contains only one element: {"x":463,"y":451}.
That array element can be instantiated as a JSONObject. It contains two name/value pairs:
"x" with the value 463.
"y" with the value 451.
So based on the code you provided, to instantiate the JSONArray:
JSONArray numbers = (JSONArray) jsonObject.get("InGameCord");
To retrieve the first (and only) element of the array into a JSONObject:
JSONObject jObj = (JSONObject) numbers.get(0);
To get the value for "x" into an int variable cast the Object returned by get() to a Number, and then get its intValue():
int value = ((Number) jObj.get("x")).intValue();
You can even do the whole thing in one line, but it's ugly:
int y = ((Number) ((JSONObject) numbers.get(0)).get("y")).intValue();

How to extract data from Json array?

Using Jsonobject I extracted data from RawmatrixData and stored it in Object:
org.json.JSONObject item = Fir.getJSONObject(i); Object value1 = item.get("RawMatrixData")`
Now i want to replace data 342771123181 with some string value, how to achieve this?
I tried with ArrayList<String> and ArrayList<ArrayList<String>>.
"LstMatrixFirmInfo": [
{
"RawMatrixData": "[[342771123181,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],[3427714486446,1,2,null,null,null,null,null,null,null,null,null,null,null,28.99,28.99,28.99,25,4.81,4.81,4.81,null,null,null,null,null,null,null,null,null]]]}
Is RawMatrixData supposed be a string like in the image or JSON Array.
If RawMatrixData is supposed to be string then maybe converted to JSONArray
I would just use string replace.
String replacedText = Fir.getString('RawMatrixData').replace('342771123181', 'foobar')
Fir.push('RawMatrixData', replacedText);
The above can be done in one line but for ease of understanding it hasn't. First line gets your string from the Json object then replace the number with foobar.
Then text is pushed back on to the json object overwriting the old value.
The above code i believe sorts out your problem based on the picture you provided.
If the RawMatrixData was supposed to be a JSON array and not a string then in that case you would have to traverse the whole array replace as you go.

java get elements inside array but know arrayname in string

String[] strsub0={"out","err","in","console()"};
String[] strsub1={"print","println","append","close","flush"};
i want to get array elements and i know the name of the array.but i know aray name in String
int i=0; //this i get through a loop ,so i can't code strsub0 in my code.
String arrayname="strsub"+i; //this is array name i want ,but it is a String.
//so i want get all elements inside array which name is strsub+i ;
//arrayname.length not return strsub0.length but i want it.
for(int z=0;z<arrayname.length;z++){
System.out.println(arrayname[z]);
}
You want an array of arrays.
String[][] strsub={{"out","err","in","console()"},
{"print","println","append","close","flush"};
Then you can get
String[] arr = strsub[i];
You could use a Map whose key is what you want and whose value is the array. Like the following:
Map<String, String[]> map = new HashMap<>(); //(assuming you have Java 7+ for the <> operator)
map.put("strsub0 ", new String[]{"out", "err", "in", "console()"});
map.put("strsub1 ", new String[]{"print", "println", "append", "close", "flush"});
Then retrieve the values like: map.get(arrayname)[i]. Of course you would have to check whether map.get(arrayname) actually exists or is null

Android - parsing JSON strings in Java

I've got a JSON string and I'm just trying to access the different properties of it and store them in Java variables. However, I keep getting an exception with the following code:
private JSONObject jObj;
private String jString;
//...
jString = result; //this is my JSON string passed from another activity
try {
jObj = new JSONObject(jString);
//int eventID = jObj.getInt("eventID");
} catch (JSONException e) {
Toast.makeText(searchResultsActivity.this, "Search results failed!", Toast.LENGTH_SHORT).show();
finish();
}
Yes I have the required imports. I've displayed jString on its own to confirm that it's valid JSON. I'm kind of lost because this seems to be the most basic thing I need to do. Thanks for any help guys.
EDIT - here is an example JSON string:
[{"eventID":"47","event_name":"test","event_address":"Test","event_duration":"3","event_date":"20110527","event_time":"1347","event_description":"Test","num_attending":"1"}]
This string is received through a PHP script where I do echo json_encode($array), where $array is the associative array creating this JSON response.
The exception I get is:
"org.json.JSONException: Value[//above JSON string//] of type org.json.JSONArray cannot be converted to JSONObject"
Eclipse did not tell you because you were trying to create a JSONObject from a JSONArray:
JSONArray jArr = new JSONArray (jString);
int eventID = jArr.getJSONObject(0).getInt("eventID");
To answer your last comment (why is this?):
From the (original documentation](http://www.json.org/java/index.html):
A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names. The internal form is an object having get() and opt() methods for accessing the values by name, and put() methods for adding or replacing values by name. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.
A JSONArray is an ordered sequence of values. Its external form is a string wrapped in square brackets with commas between the values. The internal form is an object having get() and opt() methods for accessing the values by index, and put() methods for adding or replacing values. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.
Since you were parsing a string that started with square brackets instead of curly braces, you need to parse it as a JSONArray. In your case, it is an array of size 1.
You are trying to parse a JSONArray as a JSONObject
JSONArray jarray = new JSONArray(jString);
gl!

Categories

Resources