How to make a JsonObject in a ordered way? - java

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

Related

Json to csv conversion in Spring boot

I have a csv structure like this
and I also have one json response
[
{
"ID" : "1",
"Name" : "abc",
"Mobile" : "123456"
},
{
"ID" : "2",
"Name" : "cde",
"Mobile" : "123345"
}
]
I need the output like this
If your intention is to convert directly the JSON then that baeldung solution that you were given is good.
Otherwise, the way i see it and based on the info you're giving, you will need to have a representation of that JSON in a java object that will either represent some kind of request coming from somewhere or data you're getting from your database in order to be written on a csv.
Check out these, might be useful:
https://www.codejava.net/frameworks/spring-boot/csv-export-example
https://zetcode.com/springboot/csv/

How to query JSON with wildcards and modify the results?

I'd like to be able to query a JSON object and modify it in a way that is structure-agnostic and doesn't involve marshalling to POJOs. Here's an example to illustrate.
{
"user" : [ {
"username" : "foo",
"user-id" : "1234",
"name" : {
"first-name" : "John",
"last-name" : "Smith"
},
"ssn": "123-45-6789"
}, {
"username" : "bar",
"user-id" : "1235",
"name" : {
"first-name" : "Jane",
"last-name" : "Doe"
},
"ssn": "098-76-5432"
} ]
}
What I want to do is this:
Get the ssn nodes, retrieve their values, encrypt them, put the encrypted values back in the JSON, and return the whole thing. I've found two ways to do this so far:
Marshalling to a User POJO
Writing a method that iterates over the "user"s directly and modifies the ssn value.
The problem with either approach is that I have to generate "user" specific code. This is fine when I have only one data format, but I'm going to have dozens. I want to work more agnostically. Ideally I can do this with a line like this:
List<JsonNode> ssnNodes = jsonObj.match("$.user[*].ssn");
and then just iterate over the list -- just as I can with XML using XPath. This way I can maintain a list of json-paths to query with and that is as much as I need to know about the data.
Someone please tell me there is a way to do this in Java, but I haven't found a way so far. Thanks in advance!

Android app and Database Communication: JSON Parsing and List View

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");
...
}

How to convert Map created from JSON to another Map in Java?

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")

Map inside a Map with Jackson with JSF

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

Categories