Parsing weired JSON format - java

I have to parse JSON. I am using Jackson library to parse it.
My code:
JSONObject root = (JSONObject)parser.parse(response);
JSONArray users = (JSONArray) root.get("response");
Everything would be fine if not a that number in from of elements (1192220) which actually represents a length of a structure. When I am reading it using root.get("response") this number appears to be a first element in users array. I really don't want that. Of course, I can manually truncate an array, but probably it should a better way of doing it. Any suggestions?
{
"response":[
1192220,
{
"uid":39377403,
"first_name":"John",
"last_name":"Smith",
"screen_name":"Super cool guy",
"interests":"N/A"
},
{
"uid":19439900,
"first_name":"Natalie",
"last_name":"Brook",
"screen_name":"nutaloveis",
"interests":"bike"
},
{
"uid":5857176,
"first_name":"James",
"last_name":"Mercer",
"screen_name":"alenkashishkova"
}, .....]
}

Filter it out later
If that number allways is the first element of that array, why dont you just skip it when iterating over the array later on (Start your for-loop at index 1 instead of 0)?
If numbers appear all over the array or at random indexes but you only want to get the objects (e.g. filter out all numbers), you could use javas instanceof operator and check whether it is an instance of JSONObject or Integer and then skip it respectivly.

Related

Fastest way to parse single value from JSON string

I have a string that I get from a websocket in the below JSON format. I want a very low-latency way to parse the value c associated with the key C. The key names are the same for every packet I get, but the values may differ. So, the key C will stay the same but the value can change from c to something perhaps longer. In my real life application, the number of entries inside X and Y can be much longer.
I've tried a few different approaches, including parsing a single field using Jackson [1], to parsing the full string to JsonNode, but they're all too slow (over 50 microseconds). I thought of finding the position in the String of "C" using [2], and then taking the next few characters after that, but the issue is that the value, c, is variable length so that makes it tricky.
String s = {"A":"a","B":"b","data":[{"C":"c","X":[["3.79","28.07","1"],["3.791","130.05","3"],["3.792","370.8958","5"]],"Y":[["3.789","200","1"],["3.788","1238.1709","4"],["3.787","513.4051","3"]]}'
I'd like something like this:
String valueOfC = getValueOfC(s) // return in only a few microseconds
[1] How to read single JSON field with Jackson
[2] Java: method to get position of a match in a String?
s.substring(s.indexOf("\"data\":[{\"C") + 4, s.indexOf("\"",s.indexOf("\"data\":[{\"C") + 4)));
This is sub-microsecond.

How to find first JsonArray DTD

I have a question about key-value pairs in a JSON array. Let's say I want to create a dynamic code that can be used across multiple responses where I want to pick out the first JSON array, how do I go about doing that? Currently, the code below looks for a JSON array known as 'test', but the issue here is that I can only use this code for an endpoint to spits out a JSON array that has the DTD 'test'.
What I was hoping is change the line of code below so that instead of 'test' it will be 0 or first or something like that.
httpResponse.getBody()
.getObject()
.getJSONArray("test")
.getJSONObject(0)
.get("value")
.toString();
Well, it's actually unusual to do that. Because the first item you put into a JSON object is not the first object you retrieve, JSON library puts it in an alphabetic order.
Either way, you can use the static method of JsonObject getNames() and get field names and then retrieve the first name.
EDIT:
Here is an example:
System.out.println(new JSONObject().put("second", "goes second").put("first","goes first").toString());
output:
{"first":"goes first","second":"goes second"}
And the static JSONObject.getNames():
for(String str:JSONObject.getNames(jsOb))
{
System.out.println("key="+str +", value="+jsOb.getString(str));
}
output:
key=first, value=goes first
key=second, value=goes second

How to create a dynamic array with 2 different data types

I need to create a dynamic array with data from a Excel spreadsheet using Apache-POI and Selenium.
My goal is to be able to create a dynamic array with 2 data types(int and String's)to be called to be inputted into a text field using Selenium WebDriver. I have already gotten the information to be hardcoded, however I'd like to be able to not rely on the workbook to increase the speed of my program.
General structure:
for(int i = 0; i < sheet1.getLastRowNum(); i++) {
string cell[i] = formatter.formatCellValue(sheet1.getRow(i).getCell(0)
}
The errors I get are, "Syntax Error on token "i", delete this token" and also "Type mismatch: Cannot convert from "String" to "String[]"
Would it work if you stored everything in the array as a string? You could just use String.valueOf() to convert the cell value to a string, and if you need to get it back later on as an int you could use Integer.parseInt().
You can make an array of Objects, but that could cause more trouble than it's worth. You could be adding an object into it which has a type you never accounted for, which could cause you problems later on down the line.

How can I get JSONArray values from JSONP?

I am creating an Android app that searches for recipes. I am trying to call an API which returns ingredients as JSONP. I need this data for validation purposes, so the user can't enter any invalid ingredients.
I want to get the values from the JSONArray and return the searchValue. But I do not know how to do this as the format of the data is in JSONP and not JSON.
Below is an example of what I am trying to retrieve.
set_metadata('ingredient',
[{"searchValue":"salt","description":"salt","term":"salt"},{"searchValue":"butter","description":"butter","term":"butter"},
When I tried to simply get the array, there was a JSONException. For debugging, i only wanted to return the length of the array, to see how many ingredients were inside the array.
JSONArray ingr = json.getJSONArray("");
System.out.println("Size of the array is: " + ingr.length());
But it didn't like the characters at the start and it gave me this error.
02-29 21:47:38.568 1993-2416/com.example.laptop.whatsfordinner E/JSON Parserīš• Error parsing data org.json.JSONException: Value set_metadata('ingredient' of type java.lang.String cannot be converted to JSONObject
So how can I "ignore" the first part and get values from the JSONArray?
You may do it with simple string operations, substring based on the first index of [ and the last index of ] .
Not too safe or elegant, but as long as the surrounding javascript has more or less known to you (it starts with set_metadata('ingredient', and ends with ); ) you are good to go with it.

Reading an array in mongodb?

Hi I have some trouble with arrays in mongodb. To read a document with java is no problem but to read an array what is in a document is a problem. Lets say I have a collection myCol:
{"name": "lenny linux", "gender": "m", "computers": [{"name": "computer"}, {"name": "computer2"} {"name"...}]}
So there is an array with computers. I could read the whole document with
DBCollection myCol = getCollection(...);
BasicDBObject query = new BasicDBObject();
query.put(name, "lenny linux");
DBCursor cursor = myCol.find(query);
while (cursor.hasNext()) {
System.out.print(cursor.next());
}
But I just need the names of the computers, so I have to read somehow the array. Dont get this array stuff in mongodb. And also what if I would like to delete something from a mongodb array? Its not the same as to delete a normal document... thank you for any help!
Edit: If im reading the mongodb page: http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-ValueinanArray I really dont get it. They have there an array of colors and then they are reading red like this:
db.things.find({ colors :"red" });
Why would I do this? If I want to read an array to know whats inside the array. The user dont know that there is a "red" or blue or whatever. Maybe the array colors is empty? Then I get back a null, 0 or whatever and if there are 4 colors then give me these colors, print it out. I dont have any other examples...im sorry for my bad english.
Edit2:
Ok so the new solution for me is to get the whole document where name == lenny linux (like at the first time in my code) and then to parse this document with an extern JSON parser like json-simple. Well maybe thats not the best solution, because the best solution would be to get the stuff in the array without other libs just using the mongolib... but ok its working :) If somebody knows an easier way just post it here. Thank you.
And also what if I would like to delete something from a mongodb
array? Its not the same as to delete a normal document.
http://www.mongodb.org/display/DOCS/Updating explains 2 ways:
$set: to replace the current array with a new one (fetch the previous array, remove an element or two, and update with $set)
db.users.update({name : "lenny linux"}, {$pull : { computers : { name : "computer2" } }}, false, false) to remove all elements from the array computers that have name 'computer2'.
When reaching into an array with objects (named elements), you want to use the dot notation to reach into the array.
db.myColl.find({'computers.name':'computer'});
http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-ValueinanArray
as for removing items from an array, you want to look at the $pop and $pull update functions
http://www.mongodb.org/display/DOCS/Updating
Since I was dealing with this problem in Java, and your code is in Java, here is the solution ... in java.
Basically when you get(key) a MongoDB array, it returns a com.mongodb.BasicDBList object that you can get an iterator for.
In my code, I query documents that look like this:
{
"_id": ObjectID("52d60db91f3aa664410bcde5"),
"owner": "Amy",
"trusted": [
"amy",
"paul",
"randy"
]
}
And when I ever need to find the trusted people of this document, I use ((BasicDBList) doc.get("trusted")).listIterator();
DBObject doc = collection.findOne(new BasicDBObject("owner", "Amy"))
ListIterator<Object> trustedList = ((BasicDBList) doc.get("trusted")).listIterator();
while(trustedList.hasNext()){
Object nextItem = trustedList.next();
System.out.println(nextItem.getClass()); // String
// Here I handle what to do to each name.
// I could add them to an ArrayList<String> if I needed
updateTrustee((String)nextItem);
}
I came to this solution using a few System.out.println(Object.getClass())s to know what classes I needed to cast.
The question he is asking is how does one return ALL the elements found in an array stored in a Mongo collection without knowing precisely how many or what these elements might be. You are not performing a query against a known value, rather you are simply asking for a dump of what is in the Mongo array. For example, if your Mongo array name is "colors", simply do the following:
#colors = #{$record->{colors}};
Now you have all the colors in a Perl array for you to play with.
Enjoy!

Categories

Resources