First, im learning java, so i am totally new with it, i am making a petition to a python function with xmlrpc, python sents a dictionary which contanins another dictionary inside, and various ids lists like this:
{
country_ids=[1,2,3,4,6,7,8],
state_ids=[23,22,12,12,56,12,56,72,23],
config={GLOBAL_DC=true, MAX_GLOBAL_DC=1,RET=5,COMP=1,VER=1.0}
}
So im getting this in java with:
HashMap<String, Object> data=HashMap<String, Object> xmlrpc.call...
and i am getting something like this:
{
country_ids=[Ljava.lang.Object;#7e0aa6f,
state_ids=[Ljava.lang.Object;#dc6c405,
config={GLOBAL_DC=true, MAX_GLOBAL_DC=1,RET=5,COMP=1,VER=1.0}
}
I know how to read value from the hashmap with data.get("country_ids") but, i don't know how to map/read/convert this object to get the ids inside of it.
Just in case someone cames here wondering the same or similar question, i found how has to be done:
Object [] country_ids = (Object[]) data.get('country_ids');
// To read the data of elements, something like this
for (Integer i = 0; i < country_ids.length; i++) {
Log.d("Element value of " + i.toString(),country_ids[i].toString());
}
Related
mongodb query is db.test.find({"col1":{"$ne":""}}).count(), I have tried many sources to find the solution, the "col1" must be populated from list array, please help me
I have pasted a part of my code
`
List<String> likey = new ArrayList<String>();
for (DBObject o : out.results())
{
likey.add(o.get("_id").toString());
}
Iterator<String>itkey = likey.iterator();
DBCursor cursor ;
//cursor = table.find();
HashMap<String, String> hashmap = new HashMap<String, String>();
while (itkey.hasNext())
{
System.out.println((String)itkey.next());
String keys = itkey.next().toString();
//System.out.println("keys --> "+keys);
String nullvalue = "";
Boolean listone = table.distinct(keys).contains(nullvalue);
hashmap.put(keys, listone.toString());
//System.out.println("distinct --> "+keys+" "+listone);
//System.out.println("proper str --- >"+ '"'+keys+'"');
}
Iterator<String> keyIterator = hashmap.keySet().iterator();
Iterator<String> valueIterator = hashmap.values().iterator();
while (keyIterator.hasNext()) {
//System.out.println("key: " + keyIterator.next());
while (valueIterator.hasNext()) {
//System.out.println("value: " + valueIterator.next());
//System.out.println("Key: " + keyIterator.next() +""+"value: "+valueIterator.next());
String hashkey = valueIterator.next();
}
}
`
When you post code, it helps if you indent it, so it is more readable. As I mentioned to you on another forum, you need to go back and review the Java collection classes, since you have multiple usage errors in the above code.
Here are a few things you need to do to clean up your code:
1) You don't need to use the itkey iterator. Instead, use:
for (String key : likey)
and get rid of all the itkey.next calls. Your current code only processes every second element of the List. The other ones are printed out.
2) Your HashMap will map a key to a Boolean. Is that what you want? You said you want to count the number of non-zero values for the key. So, the line:
Boolean listone = table.distinct(keys).contains(nullvalue);
is almost certainly in error.
3) When you iterate over the HashMap, you don't need the valueIterator. Instead, get the key (either from the keyIterator, or a variable you define using the simpler iterator syntax above), then use the key to get the matching value using hashmap.get(key).
This will not make your code work, but it will clean it up somewhat - at the moment it is difficult to understand what you are intending it to do.
I am new to JSON and getting confused everytime I create a new one.
I am trying to create a JSON array like this :
{
"id":"2003",
"HouseMD" :
{
"Doctor_1": "Thirteen",
"Doctor_2" : "Chase"
"Doctor_n" : "Someone"
}
}
Basically I am trying to add info dynamically from Doctor_1 to Doctor_n" in a for loop. and if I use a JSON Object I am only getting the last value when I finally print it.
How do I get something that I want?
Any help appreciated.
Thanks.
JSON arrays look like this:
{ "id":"2003", "HouseMD" : [{ "Doctor_1": "Thirteen"}, {"Doctor_2" : "Chase"}, {"Doctor_n" : "Someone" }]}
Notice the square bracket that surrounds each JSON object in the array.
Here is the link to the JSON website, which can offer more info:
JSON
Note that in order for the code below to work, you will also need the JSON library, which you can easily download from here Download Java JSON Library
I don't know the approach you are using, but based on the format you want, I would do something like this:
JSONObject data = new JSONObject();
data.put("id", "2003");
JSONObject doctors = new JSONObject();
//here I suppose you have all doctors in a list named doctorList
//and also suppose that you get the name of a doctor by the getName() method
for (int i = 0; i < doctorList.size(); ++i)
{
doctors.put("Doctor_" + (i+1), doctorList.get(i).getName();
}
data.put("HouseMD", doctors);
//then you could write to a file, or on screen just for test
System.out.println(data.toString());
However, I feel you need to become more comfortable with JSON, so try starting here.
Hi I have a strange question about java. I will leave out the background info so as not to complicate it. If you have a variable named fname. And say you have a function returning a String that is "fname". Is there a way to say reference the identifier fname via the String "fname". The idea would be something like "fname".toIdentifier() = value but obviously toIdentifier isn't a real method.
I suppose a bit of background mite help. Basically I have a string "fname" mapped to another string "the value of fname". And I want a way to quickly say the variable fname = the value of the key "fname" from the map. I'm getting the key value pair from iterating over a map of cookies in the form . And I don't want to do "if key = "fname" set fname to "value of fname" because I have a ton of variables that need to be set that way. I'd rather do something like currentkey.toIdentifer = thevalue. Weird question maybe I'm overlooking a much easier way to approach this.
Why don't you just use a simple hashmap for this?
Map<String, String> mapping = new HashMap<String, String>();
mapping.put("fname", "someValue");
...
String value = mapping.get(key); //key could be "fname"
In a way you're describing what reflection is used for:
You refer to an object's fields and methods by name.
Java Reflection
However, most of the time when people ask a question like this, they're better off solving their problem by re-working their design and taking advantage of data structures like Maps.
Here's some code that shows how to create a Map from two arrays:
String[] keyArray = { "one", "two", "three" };
String[] valArray = { "foo", "bar", "bazzz" };
// create a new HashMap that maps Strings to Strings
Map<String, String> exampleMap = new HashMap<String, String>();
// create a map from the two arrays above
for (int i = 0; i < keyArray.length; i++) {
String theKey = keyArray[i];
String theVal = valArray[i];
exampleMap.put(theKey, theVal);
}
// print the contents of our new map
for (String loopKey : exampleMap.keySet()) {
String loopVal = exampleMap.get(loopKey);
System.out.println(loopKey + ": " + loopVal);
}
Here's a link to the JavaDoc for Map.
Probably a bit similar to this: deserializing json with arrays and also I'm following on from this: Jackson multiple objects and huge json files
The json I have is pretty big so simplified it goes something like this:
{ "foo"="bar", "x"="y", "z"=[{"stuff"="stuff"}, {"more"="stuff"}, ...], ... }
I have code that looks like this:
for (Iterator<Map> it = new ObjectMapper().readValues(new JsonFactory().createJsonParser(in), Map.class); it.hasNext();) {
doSomethingWith(it.next());
}
This works nicely at iterating over the objects in the file and I can get any value I like from the object I'm in. Works fine, but the array just comes back as an ArrayList of objects. So I have to do something like:
ArrayList z = (ArrayList) it.next().get("z");
for (Object o : z) {
// Run mapper on o.
// Do stuff.
}
I'm sure this would work, but it seems a bit messy to me. Is there a better way?
Oh, whoops. Looks like the first run of the ObjectMapper does everything for me.
So I can just change my code like so:
ArrayList<Map> z = (ArrayList) it.next().get("z");
for (Map m : z) {
// Run mapper on o.
doSomethingWith(m.get("stuff");
}
and everything works splendidly.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How can I obtain values of key-value pair from a Hashmap?
QueryStats queryStats=new QueryStats();
Map parameterMap = request.getParameterMap()==null? null:new HashMap(request.getParameterMap());
System.out.println("Query2:" + parameterMap);
Collection newParamsValue=parameterMap.values();
Object newParams[]=newParamsValue.toArray();
StringBuffer strParam=new StringBuffer() ;
int l=newParams.length;
for(int i=0;i<l;i++){
strParam=strParam.append(newParams[i].toString());
}
output: Query2:{sortPrefix=[Ljava.lang.String;#1d66aa9, searsOnly=[Ljava.lang.String;#1f4bdca, globalPrefix=[Ljava.lang.String;#d81cda, indent=[Ljava.lang.String;#4e57ba, qt=[Ljava.lang.String;#1619137, wt=[Ljava.lang.String;#84c1f9, fq=[Ljava.lang.String;#1dae27f}
From this parameterMap, I want to create a query? How is it possible?
If the request is a HTTP request (and I suspect it is) and the query is a database query, then what you're trying to do is a big no-no. Always, always, always sanitize your input. Just stop for a moment and think with the mind of a malicious person trying to wreck or obtain your database content, trying to forge a HTTP request that fools your unsuspecting application into doing exactly that.
Another thing about HTTP request parameters is that they come in string arrays. If you want the string value of an input, you need to cast your values to String[] first, then grab the first element of that array. Please note that the array can be empty though, and this method only works for single value inputs, multiple selection inputs will return multiple elements.
The problem you face is that the map returned from getParameterMap maps String keys to arrays of String values. So each element of newParamsValue is a String[]. You need to do a little more work to get a sensible (comma-separated) string out of these than calling toString(). Something like this (untested) might do what you want:
ArrayList<String> toStrings(Collection requestValues) {
ArrayList<String> strings;
for (Object object : requestValues) {
String[] vals = (String[]) object;
if (vals.length() == 1) {
strings.add(vals[0]);
} else if (vals.length() > 1) {
StringBuilder sb = new StringBuilder(vals[0]);
for (int i = 1; i < vals.length(); ++i) {
sb.append(',');
sb.append(vals[i]);
}
strings.add(sb.toString());
}
}
return strings;
}