JSON string not in order - android

I want the JSON string to be in same order how I am putting it.This is my query.
object.put("name", name);
object.put("email", email);
object.put("query", query);
But in the resultant string its showing as
{"email""m#gmail.com","query":"k","name":"a"}

The order of keys in a JS object is not guaranteed. If you need a particular order, consider having a separate array of keys to preserve the ordering.
{
"order":["name", "email", "query"],
"data":{
"email":"m#gmail.com",
"query":"k",
"name":"a"
}
}
From JSON specification http://www.ietf.org/rfc/rfc4627.txt:
An object is an unordered collection of zero or more name/value pairs, where a name is a string and a value is a string, number, boolean, null, object, or array.
(emphasis mine)

Related

Android mapping does not work

Hi I have to send map to server and the server will get information from that. I'm having two piece of code for mapping first is(name and key are variables)
String user = "{ 'id':" + userId +","+"'response':{'id':"+userId+",'access':"+"'"+name+":"+key+"'"+"}}";
Map<String, Object> userMap = new Gson().fromJson(user, new TypeToken<HashMap<String, Object>>() {}.getType());
Set<String> keys = userMap.keySet();
for (String i:keys){
Log.d("user",i+" "+userMap.get(i));
}
here I concat required string and parse it and then convert it into map . This piece of code had worked. And my second set of code is
String user1 = "{id="+userId+", access="+""+name+":"+key+""+"}";
Map<String,Object> tuc = new HashMap<>();
tuc.put("id",userId);
tuc.put("access","");
Set<String> key = tuc.keySet();
for (String i:key){
Log.d("user",i+" "+tuc.get(i));
}
this code is not working,that mean server is not accepting this code. But when I print key value pairs the results are same for both codes. My lead doesn't like to use first piece of code. Can any one explain why,I'm struck in this for past two days. Thank you.Sorry for my poor English.
In Java, HashMap can only accept <key, value> pairs. It is not like Json, which in your case is in {key1:value1, key2:value2, ...} format.
Therefore, if you are intended to convert its format from {key1:value1, key2:value2, ...} into <key, value>. My suggestion is combining value2, value3, ... into an object (like String) as the value and value1 as the key.
See https://docs.oracle.com/javase/7/docs/api/java/util/HashMap.html for more details.

store two string and one integer in shared preference using hashmap

I want to store three values in shared preference
Can I store integer as third value in hashmap? As i passed null for string, what can i passed for integer?
public HashMap<String, String> getUserDetails(){
HashMap<String, String> user = new HashMap<String, String>();
// user name
user.put(KEY_NAME, pref.getString(KEY_NAME, null));
// user email id
user.put(KEY_PASS, pref.getString(KEY_PASS, null));
user.put(KEY_ID,pref.getInt(KEY_ID,));//what should i pass here??
// return user
return user;
}
you've declared your HashMap() as a map that contains String objects, so, no, you can't really just store an integer in there. However, you can convert the integer to a string if you like. Since getInt() returns a primitive int, you should use the static method Integer.toString(valuetomakeintoastring)
The second value in your call to getInt() is the default value that should be returned if the KEY value is not found in the preferences. Use some value that can't be confused as a valid value for your application.
user.put(KEY_ID,Integer.toString(pref.getInt(KEY_ID,<somedefaultintegervalue>));
Perhaps a HashMap is not the right data structure for you to use here? Perhaps you really need to define a class that contains these values together, then create a HashMap of that class?

ParseObject.put method saving strings etc as arrays? Is this a bug?

I try to save simple Object attibutes using the .put("name", data) method
ParseObject parseLibraryItem = new ParseObject("UserLibrary");
parseLibraryItem.add("movieId", 121);
parseLibraryItem.add("runtime", 134);
parseLibraryItem.add("status", "released");
parseLibraryItem.add("name", "TestParseMovie");
parseLibraryItem.add("releaseDate", "2014-11-06");
parseLibraryItem.add("imagePath", "/7k9db7pJyTaVbz3G4eshGltivR1.jpg");
parseLibraryItem.add("description", "This is just a test");
parseLibraryItem.add("tagline", "The craziest movie ever");
parseLibraryItem.add("createdBy", ParseUser.getCurrentUser());
parseLibraryItem.setACL(new ParseACL(ParseUser.getCurrentUser()));
parseLibraryItem.saveInBackground();
Here is the Parse backend
When I try to query the Object I have to then strip the returned string of the Brackets. What am I doing wrong here?
Instead of using the method add(String key, Object value), which atomically adds an object to the end of the array associated with a given key, try using the method put(String key, Object value), which adds a key-value pair to this object.
source : Android Parse API https://parse.com/docs/android/api/

How to store JSON object in SQLite database

how do I store a JSON Object in an SQLite database? What is the correct way?
one place is the blob type column. if i can convert the JSON object into byte array and use Fileoutputstream
the other idea is to store in a text column as a String
import org.json.JSONObject;
JSONObject jsonObject;
public void createJSONObject(Fields fields) {
jsonObject = new JSONObject();
try {
jsonObject.put("storedValue1", fields.storedValue1);
jsonObject.put("storedValue2", fields.storedValue2);
jsonObject.put("storedValue3", fields.storedValue3);
jsonObject.put("storedValue4", fields.storedValue4);
jsonObject.put("storedValue5", fields.storedValue5);
jsonObject.put("storedValue6", fields.storedValue6);
} catch (JSONException e) {
e.printStackTrace();
}
}
Convert JSONObject into String and save as TEXT/ VARCHAR. While retrieving the same column convert the String into JSONObject.
For example
Write into DB
String stringToBeInserted = jsonObject.toString();
//and insert this string into DB
Read from DB
String json = Read_column_value_logic_here
JSONObject jsonObject = new JSONObject(json);
An alternative could be to use the new JSON extension for SQLite. I've only just come across this myself: https://www.sqlite.org/json1.html This would allow you to perform a certain level of querying the stored JSON. If you used VARCHAR or TEXT to store a JSON string you would have no ability to query it. This is a great article showing its usage (in python) http://charlesleifer.com/blog/using-the-sqlite-json1-and-fts5-extensions-with-python/
There is no data types for that.. You need to store it as VARCHAR or TEXT only.. jsonObject.toString();
https://github.com/requery/sqlite-android allows you to query JSON fields (and arrays in them, I've tried it and am using it). Before that I was just storing JSON strings into a TEXT column. It supports FTS3, FTS4, & JSON1
As of July 2019, it still gets version bumps every now and then, so it isn't a dead project.
https://www.sqlite.org/json1.html (store and query JSON documents)
https://www.sqlite.org/fts3.html (perform full-text searches)
https://github.com/app-z/Json-to-SQLite
At first generate Plain Old Java Objects from JSON http://www.jsonschema2pojo.org/
Main method
void createDb(String dbName, String tableName, List dataList, Field[] fields){
...
Fields name will create dynamically

get array of KEYS for each element under jsonarray

I want to parse my Json array dynamically. and want to get array of KEYS for each element under jsonarray. i an getting this through iterator. but not getting the sequeance as per the output json formate.
my JSON Formate :
{
"result": "Success",
"AlertDetails": [
{
"ShipmentNumber": "SHP34",
"Customer": "BEST",
"DateCreated": "2012-08-29T04:59:18Z"
"CustomerName": "BEST"
},
{
"ShipmentNumber": "SHP22",
"Customer": "BEST",
"DateCreated": "2012-08-29T05:34:18Z"
"CustomerName": "Jelly"
}
]
}
here is My Code :
JSONArray array = jsonobject.getJSONArray("AlertDetails");
JSONObject keyarray = array.getJSONObject(0);
Iterator temp = keyarray.keys();
while (temp.hasNext()) {
String curentkey = (String) temp.next();
KEYS.add(curentkey);
}
Log.d("Parsing Json class", " ---- KEYS---- " + KEYS);
What i am getting in logcate output:
---- KEYS---- [DateCreated,CustomerName, Customer, ShipmentNumber]
What i want :
---- KEYS---- [ShipmentNumber, Customer, DateCreated,CustomerName]
The JSONObject documentation (link: http://developer.android.com/reference/org/json/JSONObject.html) has the following description for the keys() function:
public Iterator keys ()
Since: API Level 1
Returns an iterator of the String names in this object. The returned
iterator supports remove, which will remove the corresponding mapping
from this object. If this object is modified after the iterator is
returned, the iterator's behavior is undefined. The order of the keys
is undefined.
So you may get the keys but the order is undefined. You may use any of the sorting algorithms if you want the keys in any particular order.
EDIT
Since you are unaware of the order of KEYS you are getting from the WS, after receiving the data you may show the details on screen in an ordered format . After building the arraylist KEYS, you may sort it alphabetically using the following:
Collections.sort(KEYS);
This will order the Strings in the KEYS arraylist according to its natural ordering (which is alphabetically).
I just come to know when I press ctlr+space bar, in which its clearly written that behavior of the keys is undefined, orders is not maintain by keys.
Arun George said# correctly that you have to use any sorting method to achieve your goal.
and for sorting may be this link will help you.
Use GSON library from google. It has a a lot of setting to read/create/parse json array and json objects. I didn't test it to find the solution, but I think it's very simple and full featured tool and can solve the problem.
Use different library to parse json dynamically.
Below I wrote a piece of code based on Jackson JSON Processor, which is the best JSON library in my opinion
public void test() throws IOException {
String str = "{\n" +
" \"result\": \"Success\",\n" +
" \"AlertDetails\": [\n" +
" {\n" +
" \"ShipmentNumber\": \"SHP34\",\n" +
" \"Customer\": \"BEST\",\n" +
" \"DateCreated\": \"2012-08-29T04:59:18Z\",\n" +
" \"CustomerName\": \"BEST\"\n" +
" }\n" +
" ]\n" +
"}";
JsonFactory factory = new JsonFactory();
JsonParser jsonParser = factory.createJsonParser(str);
JsonToken jsonToken;
SerializedString alertDetails = new SerializedString("AlertDetails");
while (!jsonParser.nextFieldName(alertDetails)) { /* move to AlertDetails field */ }
jsonParser.nextToken(); // skip [ start array
jsonParser.nextToken(); // skip { start object
// until } end object
while ((jsonToken = jsonParser.nextToken()) != JsonToken.END_OBJECT) {
if (jsonToken == JsonToken.FIELD_NAME) {
System.out.println(jsonParser.getCurrentName());
}
}
}
It simply prints out field names in the same order as in json:
ShipmentNumber
Customer
DateCreated
CustomerName
EDIT
Naturally you can use other libraries like gson etc. But remember, as is written on json.org, that:
An object is an unordered set of name/value pairs.
and the order of keys depends on implementation and might vary in each request.
There is also the method names();
Returns an array containing the string names in this object.
Edit: returns names in undefined order. Suggestions: parse it on your own

Categories

Resources