I got JSON file like this:
{
"issues": [
{
"no1": 5509,
"date": 1451520000
},
{
"no1": 6713,
"date": 1451433600
}],
"no2": [
220380,
163950,
213330,
215250,
174300]
}
I need to create a map issues where the no1 value will be key of the map and date value will be a value of the map. I've got already method which transfers JSON to map from file, and I know how to get the issues which will be: mapFromJson.get("issues"); what I get is:
issues=[{ no1: 5509.0, date: 1.45152E9}, {no1: 6713.0, date: 1.4514336E9}]
How to convert this to map?
You can convert to JSON using JSON Library (you must to attach JAR file in your project). Also, I found a good answer for convert JSON to Map in this link. I recommended to use these functions.
Example:
JSONObject json = new JSONObject(<your_json_string>);
ArrayList issues = (ArrayList) jsonToMap(json).get("issues");
Each element in the ArrayList issues, it's already HashMap. For example, if you want to get date of no1, you could access of this way:
((HashMap)issues.get(0)).get("date")
Related
I am developing an app that communicates with Database, to retrieve values. I am using PHP for the Backend, and developing on Android Studio, using the Volley Library.
My problem is, the values that I need to send are multiple records of a table, each with four columns, for example name, age, department, and country. I am using JSON to encode these values, but I need help with how to proceed. Should I use JSON encoded 2D Arrays? if so, how to make use PHP to construct this array, as there can be variable numbers of rows.
Also, How to parse that JSON Object/Array in Android (Java)?
As of now, this is my progress:
JSON Output in browser:
{"name0":"ABC","age0":"25","department0":"Medical","country0":"XYZ","name1":"DEF","age1":"26","department1":"Engg.","country1":"XYZ"}
Here, I named each "key" of JSON using a Loop in PHP, and encoded as JSON Object. But Having Difficulty in displaying this in Android. I have used a XML layout with 4 textviews, and LISTVIEW in the main Activity XML File.
I would suggest a different json structure for encoding. Yours will get messy pretty quick if there are a lot of records. For example you would have name0, name1, ... nameN. It would be better to make an array like so:
[
{
"name" : "ABC",
"age" : 25,
"department" : "Medical",
"country" : "XYZ"
},
{
...
}
]
Notice that there are no indices concatenated to your keys. You can get the index based on the json object node's position in the array if you need it.
As for parsing it in Android, you can refer to the documentation. There is a Json parser that comes with the SDK so all you need to do is read in your string as a json array and iterate over its object nodes as needed.
For example
String jsonResponse = " ... "; // whatever the php backend gives you when you make a call to the endpoint
JSONArray arr = new JSONArray(jsonResponse);
for (int i=0; i<arr.length(); i++) {
JSONObject obj = arr.get(i);
String name = obj.getString("name");
...
}
I'm using Jackson to read/write datas from/into json files and I have an issue with the User POJO. It has a Map wich is supposed to be the ways to contact the User (so it can have from 0 to 7, depending on the Enum). I want to be able to put ways to contact using a form in JSF.
I tried something like value="#{config.user.contacts[EMAIL_PRO]}"
where of course EMAIL_PRO is an Enum (later, the user should be able to chose the Enum himself, but right now I try simple).
But when I do so, the error is
Null key for a Map not allowed in JSON
wich I understand, 'cause my debug says that the value returned is{null = null}. Now first question : since the map is empty, is JSF supposed to work simply like that ? The key "EMAIL_PRO" doesnt exists yet, but shouldn't JSF make the work done for me, and put right value with the key ?
The other question is much more about Jackson and Maps. As I said, my POJO User contains a Map, and the json file is a Map himself (containing multiple users).
Is it really possible to write a Map into this file using Jackson where the Map is Map<String, Object> and the Object contains a Map<Enum, Object> ? And if yes, how ?
Thanks for the help
PS: I cannot change either my APIs or my POJOs.
I think this is a repeated post, see How to convert hashmap to JSON object in Java
And as it says on one of the responses:
Map<String, Object> data = new HashMap<String, Object>();
data.put( "name", "Mars" );
data.put( "age", 32 );
data.put( "city", "NY" );
JSONObject json = new JSONObject();
json.putAll( data );
System.out.printf( "JSON: %s", json.toString(2) );
output:
JSON: {
"age": 32,
"name": "Mars",
"city": "NY"
}
You can also try to use Google's GSON.Google's GSON is the best library available to convert Java Objects into their JSON representation
I want to create a JSonObject with some values for call a webservice but where webservice in a order like:
{
"id" : 1
"email" : "test#test.com",
"pin" : 1234,
"age" : 25,
"firstName" : "Test First Name",
"lastName" : "Test Last Name",
"location" : "India",
"phone" : "1234567890"
}
but when I create a json object from android code it is not maintaining the order like:
requestJOB=new JSONObject();
requestJOB.put("userid",Pref.getValue(this, Const.USER_ID, requestJOB.optString("userid")));
requestJOB.put("email", Pref.getValue(this, Const.PREF_EMAIL, requestJOB.optString("email")));
requestJOB.put("pin", Pref.getValue(this, Const.PREF_PIN, requestJOB.optString("pin")));
requestJOB.put("age", Pref.getValue(this, Const.PREF_AGE, requestJOB.optString("age")));
requestJOB.put("firstname", etFirstName.getText().toString().trim());
requestJOB.put("lastname", etLastName.getText().toString().trim());
requestJOB.put("phone", etPhone.getText().toString().trim());
requestJOB.put("location", etLocation.getText().toString().trim());
I write the code my desired order but JsonObject change the order in run time. I also tried with map and LinkedList but A exception is
occured when I want to convert LIST to JsonObject.
I searched in stackoverflow where no satisfactory answer.
In this situation I don't understand exactly what I have to do.
In Android platform there is better way to serialize a object in json by using Google GSON API... Which provide all possible functionality to convert a class to their corresponding JSON. U can prepare nested jsonobject ..
Nested like json object with in a json object. Json array embedded within a json. Object
Multiple jsonarray with in a same json object. And their may be multiple variety .. Just explore this jar .. It's very easy to use and user-friendly jar. Just go and grab it .. Hopefully u feel better with this API
I used this jar in my Android project actually
I need to be able to parse sql calls from a database to json and then compare the key fields in the parsed JSON string against a json file (it's technically a BOD --Business Object Document) and if they match then I need to overwrite the json file's matching value with that of the JSON string.
e.g. I parse the sql call to this
{
"partyInfo": {
"PARTY_NAME": "NORWAY",
"STATE": "OSLO",
"PARTY_ID": "92706031",
"VERTICAL_MARKET_TOP_DESC": null,
"ATTRIBUTE20": null,
"DUNS_NUMBER": null,
"SIC_CODE": null,
"EMPLOYEES_TOTAL": null,
"ALL_ADDRESS_LINES": "HOMMENKOLLEN 23 TOPPEN 12",
"CITY": "OSLO",
"POSTAL_CODE": "1255",
"COUNTRY_NAME": "NORWAY",
"KNOWN_AS": null
}
}
and then compare it against a file that looks like this:
{
"partyInfo": {
"PARTY_NAME": string,
"STATE": string,
"PARTY_ID": number,
"SIC_CODE": string,
}
}
and overwriting values on matching keys s.t that the ending file looks like this:
{
"partyInfo": {
"PARTY_NAME": "NORWAY",
"STATE": "OSLO",
"PARTY_ID": "92706031",
"SIC_CODE": null,
}
}
So far I've been able to parse the SQL calls to JSON (using Jackson right now but I'm willing to change if need be) but I don't know how to compare against the file and overwrite only the data values that match up.
It looks like the tree model allows you to update nodes.
Here's an example:
http://wiki.fasterxml.com/JacksonInFiveMinutes#Tree_Model_Example
I may be misunderstanding what you're wanting to do, but it sounds like you could just use a for loop over the keys in the Map representing the JSON from the file, compare the values to those in the database, change any that don't match, and then write the file back out:
for(String key: fileJson.keys())
if(!fileJson.get(key).equals(sqlJson.get(key)))
fileJson.put(key, sqlJson.get(key));
// write fileJson back out to the correct file through Jackson
The simplest solution would be to parse these files into java objects (using Jackson again), compare the objects and then save what you need to save.
Otherwise you'll effectively be making something like the patch tool.
i am using google custom search engine and getting the results in JSON format.for certain queries,the JSON result has duplicate keys and hence it produces a JSONException: Duplicate key "nickname" etc..
i am using JAVA.
String str=//contains the query result in json format
JSONObject ob=new JSONObject(str) produces the exception
may know how to resolve this exception?
here is the JSON reply:
{
"kind": "customsearch#result",
"title": "The World Factbook: India - CIA - The World Factbook",
"htmlTitle": "The World Factbook: \u003cb\u003eIndia\u003c/b\u003e -",
"link": "https://www.cia.gov/library/publications/the-world-factbook/geos/in.html",
"displayLink": "www.cia.gov",
"snippet": "Jan 20, 2011 ... Features a map and brief descriptions of geography",
"htmlSnippet": "Jan 20, 2011 \u003",
"cacheid": "0n2U45w_dvkJ",
"pagemap": {
"metatags": [
{
"il.secur.classif": "UNCLASSIFIED",
"il.title": "(U) CIA The World Factbook",
"il.summary": "CIA - The World Factbook",
"il.cutdate": "20040101",
"il.secur.classif": "UNCLASSIFIED",
"il.title": "(U) CIA The World Factbook",
"il.cutdate": "20040101",
"il.secur.classif": "UNCLASSIFIED",
"il.pubdate": "20040101",
"il.postdate": "20040501",
"il.cutdate": "20040101"
}
]
}
}
here il.secur.classif occurs multiple times
JSon object, like any other object, can not have two attribute with same name. That's illegal in the same way as having same key twice in a map.
JSONObject would throw an exception if you have two keys with same name in one object. You may want to alter your object so that keys are not repeated under same object. Probably consider nickname as an array.
You need to paste the JSON object in the question.
If you really need this functionality, roll back to gson 1.6. Duplicate keys are allowed in that version.
You can make use of the Jackson library to parse JSON. I'd problems doing the same task as you with org.json's package, but I turned to Jackson and I solved it: http://wiki.fasterxml.com/JacksonHome