I have a string I would like to put into an ArrayList of Strings. The string is basically a JSONObject so I might just be using the wrong methods.
The way the string looks is:
String all = "{"users":
[
[{"login":"username1"},{"password":"test1"},{"index":"1"}],
[{"login":"username2"},{"password":"test2"},{"index":"2"}]
]}";
All I want is the JSONObject values so my pattern gives me this String:
String part = "[
[{"login":"username1"},{"password":"test1"},{"index":"1"}],
[{"login":"username2"},{"password":"test2"},{"index":"2"}]
]";
This is what I want:
user[0] = "[{"login":"username1"},{"password":"test1"},{"index":"1"}]";
user[1] = "[{"login":"username2"},{"password":"test2"},{"index":"2"}]";
When I try to group everything in between the inner [ ] it just returns everything in the outer [ ].
I have tried:
String[] user = new String[20];
Pattern p = Pattern.compile("(\\[\\{.*\\}\\])");
Matcher m = p.matcher(part);
while(m.find()){
user = m.group().split("\\],\\[");
}
This approach gets rid of the ],[ which I'm using as a delimiter.
Class User {
private String username;
private String password;
}
Class Users{
LinkedList<User> users;
}
You can use any available JSON marshallers like Jackson etc to deserialize the string into a Users.
So I took the advice from the comment section and sure enough using JSON methods was the way to go. I would still like to see if it was possible to accomplish with regular expressions.
ArrayList<String> myList = new ArrayList<String>();
JSONObject obj = new JSONObject();
JSONArray arr = new JSONArray();
obj = {"user":"[[{},{},{}],[{},{},{}]]";
// This gives me the outer JSONArray
arr = obj.getJSONArray("user");
// This iterates through the outer JSONArray assigning each inner JSONArray
// to my ArrayList as strings.
for( int i = 0; i < arr.length(); i++){
myList.put(arr.getJSONArray(i).toString());
}
Related
Good day!
I have an array of json objects like this :
[{
"senderDeviceId":0,
"recipientDeviceId":0,
"gmtTimestamp":0,
"type":0
},
{
"senderDeviceId":0,
"recipientDeviceId":0,
"gmtTimestamp":0,
"type":4
}]
For some reasons I need to split then to each element and save to storage. In the end I have many objects like
{ "senderDeviceId":0,
"recipientDeviceId":0,
"gmtTimestamp":0,
"type":0
}
{
"senderDeviceId":0,
"recipientDeviceId":0,
"gmtTimestamp":0,
"type":4
}
After some time I need to combine some of them back into json array.
As I can see - I can get objects from storage, convert them with Gson to objects, out objects to a list, like this:
String first = "..."; //{"senderDeviceId":0,"recipientDeviceId":0,"gmtTimestamp":0,"type":0}
String second = "...";//{"senderDeviceId":0,"recipientDeviceId":0,"gmtTimestamp":0,"type":4}
BaseMessage msg1 = new Gson().fromJson(first, BaseMessage.class);
BaseMessage msg2 = new Gson().fromJson(second, BaseMessage.class);
List<BaseMessage> bmlist = new ArrayList<>();
bmlist.add(msg1);
bmlist.add(msg2);
//and then Serialize to json
But I guess this is not the best way. Is there any way to combine many json-strings to json array? I rtyed to do this:
JsonElement elementTm = new JsonPrimitive(first);
JsonElement elementAck = new JsonPrimitive(second);
JsonArray arr = new JsonArray();
arr.add(elementAck);
arr.add(elementTm);
But JsonArray gives me escaped string with json - like this -
["{
\"senderDeviceId\":0,
\"recipientDeviceId\":0,
\"gmtTimestamp\":0,
\"type\":4
}","
{
\"senderDeviceId\":0,
\"recipientDeviceId\":0,
\"gmtTimestamp\":0,
\"type\":0
}"]
How can I do this?
Thank you.
At the risk of making things too simple:
String first = "...";
String second = "...";
String result = "[" + String.join(",", first, second) + "]";
Saves you a deserialization/serialization cycle.
I am not able to format below string :
"Sony,20,30,40;LG,1,4,8"
In below JSON format:
"reported": {
"SETS": [
{
"prodName": "Sony",
"fmtd": "20",
"lmtd": "30",
"lm": "40"
},
{
"prodName": "LG",
"mtd": "1",
"lmtd": "4",
"lm": "8"
}
]
}
I tried below code but not getting proper results.
String stringFromProc = "SONY,20,30,40;LG,1,4,8";
String[] array1 = stringFromProc.split("[\\;]");
JSONObject jsonSubObject = null;
JSONObject jsonFinal = new JSONObject();
JSONArray jsonArrayRET = new JSONArray();
for(int i=0;i<array1.length;i++){
String []array2 = array1[i].split("[\\,]");
for(int j=0;j<array2.length;j++){
System.out.println(array2[j]);
jsonSubObject = new JSONObject();
jsonSubObject.put("prodName", array2[0]);
jsonSubObject.put("mtd", array2[1]);
jsonSubObject.put("lmtd", array2[2]);
jsonSubObject.put("lm", array2[3]);
jsonArrayRET.add(jsonSubObject);
jsonFinal.put("reported", jsonArrayRET);
}
}
But getting this format:
{"SETS":[{"lm":"40","lmtd":"30","mtd":"20","prodName":"MNP"},{"lm":"40","lmtd":"30","mtd":"20","kpiName":"MNP"},{"lm":"40","lmtd":"30","mtd":"20","kpiName":"MNP"},{"lm":"40","lmtd":"30","mtd":"20","kpiName":"MNP"},]}
I know that I am making loop after splitting the comma separated array but not able to get the correct approach of how to split. Someone please suggest.
Just remove the internal loop
String stringFromProc = "SONY,20,30,40;LG,1,4,8";
String[] array1 = stringFromProc.split(";"); // simply use ;
// array1[0] = SONY,20,30,40
// array1[1] = LG,1,4,8
JSONObject jsonSubObject = null;
JSONObject jsonFinal = new JSONObject();
JSONArray jsonArrayRET = new JSONArray();
for(int i=0;i<array1.length;i++){
String []array2 = array1[i].split(","); // simply use ,
// create jsonobjects
// when i=0 mean for sony and next time i = 1 mean for LG
jsonSubObject = new JSONObject();
jsonSubObject.put("prodName", array2[0]);
jsonSubObject.put("mtd", array2[1]);
jsonSubObject.put("lmtd", array2[2]);
jsonSubObject.put("lm", array2[3]);
// put every object in array
jsonArrayRET.add(jsonSubObject);
}
// finally put array in reported jsonobject
jsonFinal.put("reported", jsonArrayRET);
Note : ; and , are not special regular expressions characters so no escaping \\ is required and instead of long info just read about character class []
Move
jsonFinal.put("reported", jsonArrayRET);
outside of 2nd loop, you are overwritting reported object.
for(int i=0;i<array1.length;i++){
String []array2 = array1[i].split("[\\,]");
for(int j=0;j<array2.length;j++){
System.out.println(array2[j]);
jsonSubObject = new JSONObject();
jsonSubObject.put("prodName", array2[0]);
jsonSubObject.put("mtd", array2[1]);
jsonSubObject.put("lmtd", array2[2]);
jsonSubObject.put("lm", array2[3]);
jsonArrayRET.add(jsonSubObject);
}
jsonFinal.put("reported", jsonArrayRET);
}
I'm trying some code where I want to compare strings i've grabbed from json to certain values. However the if statements never trigger. I have confirmed the values of the instances are set properly, and can be printed out.
//MAKING CLASSES
Collection collection = new ArrayList();
Event ev = new Event();
ev.name = "sven";
ev.source = "src10";
Event2 ev2 = new Event2();
ev2.name = "type";
ev2.data = "somedata";
collection.add(ev);
collection.add(ev2);
//MAKING A BUNCH OF CLASSES TO JSON
Gson gson = new Gson();
String json = gson.toJson(collection);
JsonParser parser = new JsonParser();
JsonArray array = parser.parse(json).getAsJsonArray();
//JSON TO JAVA
for (int i = 0; i < array.size(); i++) {
JsonObject nameObject = array.get(i).getAsJsonObject();
String nameString = nameObject.get("name").toString();
if (nameString.equals("sven")) {
System.out.println("this is sven");
Event event = gson.fromJson(array.get(i), Event.class);
}
else if (nameString.equals("type")) {
System.out.println("this is type");
Event2 event2 = gson.fromJson(array.get(i), Event2.class);
}
else{
System.out.println("nothing");
}
}
According Gson API your call to 'nameObject.get("name")' will return JsonElement. This means you should use 'getAsString()' method instead of 'toString()':
String nameString = nameObject.get("name").getAsString();
'toString()' method is designed (in general) for debugging purposes. And should be used very carefully in program logic.
You need to know that the implementation of toString() in JsonElement class is such that it will return the String inclusive of "".
To make it easier to understand look into the following code
JsonObject json = new JsonObject();
json.addProperty("hello", "tata");
System.out.println(json.get("hello").toString()); // Prints "tata"
System.out.println(json.get("hello").getAsString()); // Prints tata
so internally your code is comparing "sven" and sven which will return not equal
I have a web system that returns a json string with the data that I need in an Android App. The string is below:
[
{"id":1,
"title":"Remove ViRuSeS",
"tagline":"Remove ViRuSeS",
"body":"Body",
"image":"index.jpg",
"steps":[
{"id":2,
"title":"Step 1",
"body":"Download Things!",
"position":1}
]
}
]
It should return an array of objects, with one of the object's items also being an array of items.
I am familiar with gson and have gotten this working in the past, but I always had to simplify my data down to just an object, which makes me end up have to make multiple calls to get the data.
Is there a good way to do this without having to map all of the possible values back into classes?
My last attempt was to just try to get something simple out of this and am getting a NullPointerException on the second of these lines:
userDet = new JSONObject(string);
JSONArray userDetJson = userDet.getJSONArray("Steps");
change it to "steps" and not "Steps" , It will fix it:
userDet = new JSONObject(string);
JSONArray userDetJson = userDet.getJSONArray("steps");
The full parsing method:
JSONArray mainArray = new JSONArray(json);
for (int i = 0 ; i < mainArray.length() ; i ++)
{
JSONObject currentItem = array.getJSONObject(i);
String title = currentItem.getString("title");
String body = currentItem.getString("body ");
....
JSONArray currentItemStepsArray = currentItem.getJSONArray("steps");
for (int j = 0 ; j < currentItemStepsArray.length() ; j ++)
{
....
}
}
Here, try this:
JSONArray topLevelArr = new JSONArray(json);
JSONArray stepArr = topLevelArr.getJSONObject(0).getJSONArray("steps");
I was using JSONParser to obtain results of a search, for that I followed this tutorial: http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
The thing is that, the API I am using gives the results like this:
{"response":[50036,{"aid":88131498,"owner_id":61775052,"artist":"Terror Squad","title":"Lean Back (OST Need For Speed Underground 2)","duration":249,"url":"http:\/\/cs4408.vkontakte.ru\/u59557424\/audio\/7f70f58bb9b8.mp3","lyrics_id":"3620730"},{"aid":106963458,"owner_id":-24764574,"artist":"«Dr. Dre ft Eminem, Skylar Grey (Assault Terror)","title":"I Need A Doctor (ASSAULT TERROR DUBSTEP REMIX)»","duration":240,"url":"http:\/\/cs5101.vkontakte.ru\/u79237547\/audio\/12cd12c7f8c2.mp3","lyrics_id":"10876670"}]}
My problem comes when I have to parse the first integer (here it is 50036) which is the number of results found.
I don't know how to read that integer.
This is my code:
private void instance(String artisttrack){
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
String jsonurl = new String( "https://api.vk.com/method/audio.search?access_token=ACC_TOKEN&api_id=ID&sig=SIG&v=2.0&q=" + artistname + artisttrack + "&count=5");
JSONObject json = jParser.getJSONFromUrl(jsonurl);
try {
// Getting Array of Contacts
response = json.getJSONArray(TAG_RESPONSE);
// looping through All Contacts
for(int i = 0; i < response.length(); i++){
JSONObject c = response.getJSONObject(i);
// Storing each json item in variable
//int results = Integer.parseInt(c.getString(TAG_RESULTS));
String aid = c.getString(TAG_AID);
String owner_id = c.getString(TAG_OWNER_ID);
String artist = c.getString(TAG_ARTIST);
String title = c.getString(TAG_TITLE);
String duration = c.getString(TAG_DURATION);
// Phone number is agin JSON Object
//JSONObject phone = c.getJSONObject(TAG_PHONE);
String url = c.getString(TAG_URL);
String lyrics_id = c.getString(TAG_LYRICS_ID);
Log.e("áaaaaaaaaaaaaaa", url);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
The JSONParser.java is like written in the tutorial.
And here 2 lines of the logcat error:
W/System.err(10350): org.json.JSONException: Value 50036 at 0 of type java.lang.Integer cannot be converted to JSONObject
W/System.err(10350): at org.json.JSON.typeMismatch(JSON.java:100)
Your JSON sample is a poor way to organize the results: mixing the number in with the result objects. Is the number supposed to indicate the number of objects in the array or something else?
If you can assume that this number will always be the first element, and according to this then it's supposed to work this way, you can try to read the first value of the array outside the loop:
response = json.getJSONArray(TAG_RESPONSE);
// from your example, num will be 50036:
num = response.getInt(0);
for (int i = 1; i < response.length(); i++){
JSONObject c = response.getJSONObject(i);
Note that the example in the linked documentation has this number as a string:
{"response":
["5",
{"aid":"60830458","owner_id":"6492","artist":"Noname","title":"Bosco",
"duration":"195","url":"http:\/\/cs40.vkontakte.ru\/u06492\/audio\/2ce49d2b88.mp3"},
{"aid":"59317035","owner_id":"6492","artist":"Mestre Barrao","title":"Sinhazinha",
"duration":"234","url":"http:\/\/cs510.vkontakte.ru\/u2082836\/audio\/
d100f76cb84e.mp3"}]}
But JSONArray.getInt() will parse the String as an int for you.
And notice that some of the values in the objects in your array are also numbers, you may want to read those as int also:
int aid = c.getInt(TAG_AID);
int owner_id = c.getInt(TAG_OWNER_ID);
int duration = c.getInt(TAG_DURATION);
A lot of the values you are trying to parse in are not String objects, specifically "aid", "owner_id", and "duration". Use the correct method to retrieve values. For example:
int aid = c.getInt(TAG_AID);
int owner_id = c.getInt(TAG_OWNER_ID);
String artist = c.getString(TAG_ARTIST);
String title = c.getString(TAG_TITLE);
int duration = c.getInt(TAG_DURATION);
edit: Another error that I missed is you start your array with 50036. This is not a JSONObject and cannot be parsed as so. You can add a conditional statement to check if it's array index 0 to parse the int using getInt(), and then parse as JSONObjects for the rest of the array values.
Try changing
response = json.getJSONArray(TAG_RESPONSE);
into
response = (JSONObject)json.getJSONArray(TAG_RESPONSE);
I dont have any experience with JSONObject, but works often with type mismatches.
Try putting 50036 in quotes like this "50036" .