I'm making a game (trying...) like Risk for college with Spring MVC. I'm using JPA and I need to save the state of the game (whose player turn is, units in countries,etc.) in a String field coded with JSON, and that's what's driving me crazy.
First, I create the game with other information (id, user's owner, state...) and when It starts for the first time I want to generate the JSON and set it to the entity and save it. I tried with entityManager.merge(game) but when I look at the DB the JSON field is null. I tried to make namedquery and nativequery but at the JSON string have " it's a mess.
Any ideas why it's not saving with merge?
The code is something like:
HomeController.class
public String getGame(#PathVariable("idGame") long idGame,
Model model) throws IOException {
Game g = GameDao.getGame(idGame);
if (g.getJson == null) {
g.initializeGame(); // it sets the json attribute
GameDao.update(entityManager, g);
}
}
GameDAO.class
#Transactional
public static Game update(EntityManager entityManager, Game g) {
try {
entityManager.merge(g); // if I debug here g has the json attribute setted
return entityManager.find(Game.class, g.getId()); // the game object that's returned hasn't the json field setted
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
This is the repo https://github.com/alvardsoler/reinvasion but it's the most in Spanish. It's for september exams and I don't have too much time so I want to do it very sketchy first, and then if I have time I'll do it good. If I can't save the JSON info in the DB I will save it in a file in the server with the id of the game or something like that.
I found the problem. I make the update with createNativeQuery:
Query q = entityManager.createNativeQuery("update Game g SET g.json=:json where g.id=:id");
q.setParameter("json", g.getJson());
q.setParameter("id", g.getId());
q.executeUpdate();
And added #Transactional in the GameDAO's method and in the HomeController method...
It is rather easy using the library GSON (jsonString ):
// Create the JSON string like this first
MyObject yourObject = /* Create an object here */;
Gson gson = new Gson();
String jsonString = gson.toJson(yourObject);
// Create an object from the JSON string like this afterwards
MyObject newObject = gson.fromJson(jsonString , MyObject.class);
Related
I have the below Stream class that is getting returned from DB:
Stream<Transaction> transctions=transRepository.findByTransctionId();
public class Transaction{
String transctionId;
String accountId;
String transName;
String accountName;
}
Now my Requirement is as below:
Transaction entity has 4 fields. So, from DB all the 4 fields were fetched by Jpa.
But client who needs this data ,he has sent the columnsName in list that he is looking from Transaction model
List<String> columnNames=Arrays.asList("transctionId","accountName")
I have post this data to Kafka.I have to take each Transction from this stream post it to kafka.
But cline is looking for only this 2 fields "transctionId","accountName" should go as part of Transaction in Kafka instead of all 4 fields.
The data should go in form of json to Kafa having below format:
{
"transctionId":"1234",
"accountName" :"test-account"
}
Basically only those fields should go to kafka which they have asked for instead of converting the whole pojo to json and send it.
Is there any way to achieve that?
If you need to invoke a method, but you only have its name, the only way I know is via reflection. I would do it like this:
Stream<Transaction> transctions=transRepository.findByTransctionId();
List<Transaction> outTransactions = new ArrayList<>();
List<String> columnNames = new ArrayList<>();
transactions.forEach(tr -> {
Transaction outTransaction = new Transaction();
columnNames.forEach( col -> {
try {
var getMethod = tr.getClass().getMethod("get" + StringUtils.capitalize(col));
Object value = getMethod.invoke(tr);
String valueStr = value instanceof String ? value.toString() : "";
var setMethod = outTransaction.getClass().getMethod("set" + StringUtils.capitalize(col));
setMethod.invoke(outTransaction, valueStr);
} catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
e.printStackTrace();
}
});
outTransactions.add(outTransaction);
});
There is a lot of traversing, but with the requirements you have, this is the generic solution I can come up with. Another shortcoming to this solution is the creation of new Transaction objects. Which means that if Transactions are many, memory usage can grow. Maybe this solution can be optimised to take advantage of streaming the transactions from the DB.
Another way to do it is to have different endpoints for each known set of properties that the client sends you. For example:
#GetMapping("/transaction_id_and_name")
List<Transaction> getTransactionsIdAndName() {
... obtain Transactions, return a new list of Transactions, with transaction_id and name ... }
#GetMapping("/transaction_id_and_status")
List<Transaction> getTransactionsNameAndStatus() {...}
If we wanna get an object ID we should do this:
String objectId = gameScore.getObjectId();
but what if we wanna get an object ID by a query? Like this:
ParseQuery<ParseObject> query = ParseQuery.getQuery("mytable");
query.whereEqualTo("Title", "Adrians Book");
List<ParseObject> results = null;
try {
results = query.find();
if(!results.isEmpty()) {
String objectId = results.getObjectId();
}
} catch (com.parse4cn1.ParseException e) {
Dialog.show("Err", "Something went wrong.", "OK", null);
}
Sounds interesting don't you think? I wish it could be possible. As you can see in this example the query will get a value from a specific object in the table which could track for the object ID then returning it as well. ParseQuery class should be implemented with getObjectId(). Because by this way applications always could have access to object IDs from the query even after applications get restarted so in the first example the gameScore which is actually an instance of ParseObject would lost reference to the Database after restarting. Getting object IDs by the query it would be able to program applications to get object IDs automatically without the need of doing it manually nor depending on instances of ParseObject.
#Shai Almog: Thank you very much for taking your time to look at the ParseQuery documentation.
I accidentally figured out how to get this done!
ParseQuery<ParseObject> query = ParseQuery.getQuery("mytable");
query.whereEqualTo("Title", "Adrians Book");
List<ParseObject> results = null;
try {
results = query.find();
if(!results.isEmpty()) {
String objectId = results.get(0).getObjectId();
System.out.println(objectId);
}
} catch (com.parse4cn1.ParseException e) {
Dialog.show("Err", "Something went wrong.", "OK", null);
}
Yep, after adding the method .get(index) it allows you to access the method .getObjectId() since results is a list of a ParseObject, then the respective objectId of your query result will be printed in the console! I'm pretty glad it's working because I won't need to serialize each object for now which would be a pain.
Also if you wanna set an instance of ParseObject with an existing objectId in case you need to update something in your Database, you can use this example:
ParseObject po = ParseObject.create("mytable");
po.setObjectId(//YOUR DESIRED OBJECTID HERE, AS LONG AS IT EXISTS IN THE DATABASE);
As far as I know you need to get the whole object then query it's ID. I don't see a query id method here https://github.com/sidiabale/parse4cn1/blob/41fe491699e604fc6de46267479f47bc422d8978/src/com/parse4cn1/ParseQuery.java
In my Android app, I used Gson in order to save/load the object's Arraylist in SharedPreferences. Follows are my code using Gson.
public static ArrayList<RequestModal> getModalList(Context ctx) {
Gson gson = new Gson();
String json = getSharedPreferences(ctx).getString("ModalList", new Gson().toJson(new ArrayList<>()));
Type type = new TypeToken<ArrayList<RequestModal>>() {}.getType();
return gson.fromJson(json, type);
}
In here "RequestModal" is the simple object include a bit of strings and integers.
It works well in case "online". But if internet is offline, forever works on below code.
Type type = new TypeToken<ArrayList<RequestModal>>() {}.getType();
How can I solve it? What is the way implement the feature like this with/without using Gson? Please help me anyone having a good idea.
Thank you in advance.
You can implement this without Gson:
public static EpisodeDetails parseEpisodeDetails(String content) {
EpisodeDetails episodeDetails = new EpisodeDetails();
try {
JSONObject jsonObject = new JSONObject(content);
episodeDetails.title = jsonObject.getString("title");
episodeDetails.subTitle = jsonObject.getString("subtitle");
episodeDetails.synopsis = jsonObject.getString("synopsis");
episodeDetails.ends_on = jsonObject.getString("ends_on");
JSONArray images = jsonObject.getJSONArray("image_urls");
if (images.length() > 0) {
episodeDetails.image_url = images.getString(0);
}
} catch (JSONException e) {
e.printStackTrace();
return null;
}
return episodeDetails;
}
What I'm doing is just taking the String, in your case the one saved on the shared prefs called ModalList and inserting the values on my structure, on my code the structure is called EpisodeDetails, on your code the correspondent is RequestModal. If you don't want to do it via code and want to try another library I recommend Jackson.
Another thing, on this line:
String json = getSharedPreferences(ctx).getString("ModalList", new Gson().toJson(new ArrayList<>()));
Your second parameter is not necessary. getString takes the key to load as first parameter and a default value as second paramter (in the case of empty result). You could change this to "" or null.
Well, another solution to your problem could be TinyDB. It makes use of Gson to save ArrayLists of objects in sharedPrefs, its usage is so simple as:
Person person = new Person("john", 24);
tinydb.putObject("user1", person);
ArrayList<Person> usersWhoWon = new ArrayList<Person>();
tinydb.putListObject("allWinners", usersWhoWon);
and that's it, check out my link given above to see the usage details.
I realize my questions have been asked a lot but I have spent a considerable amount of time scouring both SO and google trying to get a better understanding of this concept with no success. I've seen many different implementations, which is what leads me to get some advice about my specific situation.
MY OBJECTIVE
I need to perform a post request to a php file and the goal is to ultimately populate fields in a list activity with some of the json data.
HTTP POST RESPONSE
Here is the format of the response data I'm getting back from the server, which appears to be a JSON object of arrays(?).
{"expense":[{"cat_id_PK":237,"cat_name":"Name1","cat_amount":"100.00","is_recurring":0},
{"cat_id_PK":238,"cat_name":"Name2","cat_amount":"200.00","is_recurring":0},
{"cat_id_PK":239,"cat_name":"Name3","cat_amount":"300.00","is_recurring":0},
{"cat_id_PK":240,"cat_name":"Name4","cat_amount":"400.00","is_recurring":0}],
"expense_rec": [{"cat_id_PK":207,"cat_name":"Name5","cat_amount":"500.00","is_recurring":1}]}
FIRST QUESTION
The code below is what I'm using to read the response. Is this how I should be handling that? It seems weird to get a json encoded response and then change it to a string, only to try and access elements of a json object again. Am I on the wrong track here?
//This code is in the doInBackground method of my "sendPostRequest" async task.
HttpResponse httpResponse = httpClient.execute(httpPost);
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
stringBuilder.append(bufferedStrChunk);
}
//Returns string to onPostExecute()
return stringBuilder.toString();
SECOND QUESTION
I have another file called "PostResponse.java" that holds the following code I modeled after a tutorial online. I'm unsure of how to interact with this class from the onPostExecute method. How can I access say, the first item in the first object (something like in PHP where you could do: expense[0]['cat_name']). I've tried to do this various ways with no success. Here is the PostResponse.java class:
public class PostResponse {
public Integer cat_id_PK;
public String cat_name;
public BigDecimal cat_amount;
public Integer is_recurring;
public int getID() {
return this.cat_id_PK;
}
public void setID(int cat_id_PK){
this.cat_id_PK = cat_id_PK;
}
public String getName() {
return this.cat_name;
}
public void setName(String cat_name) {
this.cat_name = cat_name;
}
public BigDecimal getAmount() {
return this.cat_amount;
}
public void setAmount(BigDecimal cat_amount) {
this.cat_amount = cat_amount;
}
public int getRecurring() {
return this.is_recurring;
}
public void setRecurring(int is_recurring) {
this.is_recurring = is_recurring;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("*** Categories ***");
sb.append("cat_id_PK="+getID()+"\n");
sb.append("cat_name="+getName()+"\n");
sb.append("cat_amount="+getAmount()+"\n");
sb.append("is_recurring="+getRecurring()+"\n");
return sb.toString();
}
}
and here is the content of my onPostExecute method:
protected void onPostExecute(String result) {
super.onPostExecute(result);
Gson gson = new Gson();
PostResponse response = gson.fromJson(result, PostResponse.class);
System.out.println(result);
}
Like I said originally, my ultimate goal is to populate these items to a list activity, but at this point I'd settle for just knowing how to get at specific elements. However, if anyone would like to include how to populate a list activity in their response, it would save me a lot more headaches, as nothing with java is coming easy for me!
FIRST QUESTION
The code below is what I'm using to read the response. Is this how I should be handling that? It seems weird to get a json encoded response and then change it to a string, only to try and access elements of a json object again. Am I on the wrong track here?
It's one way of handling the http response. A "json encoded response" is little more than a text-based response, so converting it into a string on the receiving end would make sense. That is, the json you receive isn't an 'object' as far as Java is concerned: it's just textual representation of an object (or a bunch of objects in your case), received as a stream of bytes.
That being said, you can potentially shorten your code by skipping the string(builder) part. Gson provides an alternative constructor that takes a Reader instance, for which you can suppy the BufferedReader in your code snippet.
As a side note: the conversion of textual json into Java objects is a potentially 'heavy' operation. As such, you'd best avoid doing it on the main/ui thread, so just move it into the doInBackground() method of your AsyncTask (and change types appropriately).
SECOND QUESTION
I have another file called "PostResponse.java" that holds the following code I modeled after a tutorial online. I'm unsure of how to interact with this class from the onPostExecute method. How can I access say, the first item in the first object (something like in PHP where you could do: expense[0]['cat_name']). I've tried to do this various ways with no success.
You're close, but if you look more closely to the json sample, you'll see that your PostResponse class is not a good match for it:
{
"expense": [
{
"cat_id_PK": 237,
"cat_name": "Name1",
"cat_amount": "100.00",
"is_recurring": 0
},
{
"cat_id_PK": 238,
"cat_name": "Name2",
"cat_amount": "200.00",
"is_recurring": 0
},
{
"cat_id_PK": 239,
"cat_name": "Name3",
"cat_amount": "300.00",
"is_recurring": 0
},
{
"cat_id_PK": 240,
"cat_name": "Name4",
"cat_amount": "400.00",
"is_recurring": 0
}
],
"expense_rec": [
{
"cat_id_PK": 207,
"cat_name": "Name5",
"cat_amount": "500.00",
"is_recurring": 1
}
]
}
Consider the more hierarchical formatting above. On the first level there are two (json) objects: expense and expense_rec (both contain 0...* elements, as the square brackets indicate). That means that whatever class you're going to be trying to map the json onto, should define these fields too. If you now look at your PostResponse class, it should become obvious that in its current form it in fact models one of the child objects of the aforementioned fields.
Basically, the classes to map the json onto, should look somewhat like this:
PostResponse:
public class PostResponse {
public ExpenseItem[] expense;
public ExpenseItem[] expense_rec;
// List<ExpenseItem> is also supported
// getters & setters
}
ExpenseItem:
public class ExpenseItem {
public Integer cat_id_PK;
public String cat_name;
public BigDecimal cat_amount;
public Integer is_recurring;
// getters & setters
}
With the model classes defined, try to let Gson work its magic again. If all goes well, you should be able to access the data in a way similar to what you're used to in PHP:
// map json to POJOs
PostResponse response = new Gson().fromJson(bufferedReader, PostResponse.class);
// retrieve the cat_name for the first item (assuming there is one)
String catName = response.getExpense()[0].getName();
... or any of the other fields through the getters defined in ExpenseItem.
Once you have this part working, it's going to be fairly straightforward to supply the array or list of expenses to an adapter (have a look at ArrayAdapter in the Android framenwork) and bind that adapter to a ListView.
The answer is yes, you will get the response in InputStream
For your second question check this out - jsonschema2pojo this can be helpful while creating models for your JSON data.
Then to use GSON
Gson gson = new Gson();
YourObj yourObj = (YourObj) gson.fromJson(result, YourObj.class);
The answer is yes.Response is received as InputSteam
protected void onPostExecute(String result)
{
super.onPostExecute(result);
Gson gson = new Gson();
PostResponse response = gson.fromJson(result, PostResponse.class);
System.out.println(result);
}
This code section mostly means that after an AsyncTask that get web Response and get the String format json response,this onPostExecute will be called with that Stringfied json.
Gson gson = new Gson();
Gson is a library supported by Google for android to deserialization into your class OBject.
gson.fromJson(result, PostResponse.class);
This method is the real process of deserialization. result is Stringfied json and the second is the Target class you want to deserialize into.
This will return a PostResponse Object and you can use it now.
For the json data (
{"expense":[{"cat_id_PK":237,"cat_name":"Name1","cat_amount":"100.00","is_recurring":0},
{"cat_id_PK":238,"cat_name":"Name2","cat_amount":"200.00","is_recurring":0},
{"cat_id_PK":239,"cat_name":"Name3","cat_amount":"300.00","is_recurring":0},
{"cat_id_PK":240,"cat_name":"Name4","cat_amount":"400.00","is_recurring":0}],
"expense_rec": [{"cat_id_PK":207,"cat_name":"Name5","cat_amount":"500.00","is_recurring":1}]}),
it contains two different arrays here, one is "expense" and another is "expense_rec". So if you want to populate these items to a list activity, you can try the follow methods.
protected void onPostExecute(String result) {
super.onPostExecute(result);
JSONObject jsonObject = new JSONObject(builder.toString());
Log.i(TAG, "jsonObject is : " + jsonObject.toString());
//this is the first array data
JSONArray jsonArray = jsonObject.getJSONArray("expense");
Log.i(TAG, "Array length is: " + jsonArray.length());
for(int i = 0; i < jsonArray.length(); i++){
JSONObject jsoObj = jsonArray.getJSONObject(i);
String name = jsoObj.getString("cat_name");
Log.i(TAG, "file name is: " + name);
}
//this is the second array data
jsonArray = jsonObject.getJSONArray("expense_rec");
for(int i = 0; i < jsonArray.length(); i++){
JSONObject jsoObj = jsonArray.getJSONObject(i);
String name = jsoObj.getString("cat_name");
Log.i(TAG, "file name is: " + name);
}
}
So, I've been trying for some time to parse this nested JSON string. If this was regular Java, or even php,I'm sure this would have been done long ago. Unfortunately I'm stuck with J2ME on this one. Through some searching I found that there exits a lone JSON parser. This I found through some digging on a similar question. I've tried some work on my own, with an example on another question. However, I'm still having a few difficulties. I will explain now.
This is the JSON string I'm trying to parse:
{"Result":"Success","Code":"200","CustomerInfo":"{\"clientDisplay\":{\"customerId\":429,\"globalCustNum\":\"0012-000000429\",\"displayName\":\"Hugo Daley\",\"parentCustomerDisplayName\":\"G-KINGSTON\",\"branchId\":12,\"branchName\":\"Bangalore_branch1244724101456\",\"externalId\":\"123000890\",\"customerFormedByDisplayName\":\"New User1244724101456\",\"customerActivationDate\":\"2012-06-17\",\"customerLevelId\":1,\"customerStatusId\":3,\"customerStatusName\":\"Active\",\"trainedDate\":null,\"dateOfBirth\":\"1950-10-10\",\"age\":61,\"governmentId\":\"100000090\",\"clientUnderGroup\":true,\"blackListed\":false,\"loanOfficerId\":17,\"loanOfficerName\":\"New User1244724101456\",\"businessActivities\":null,\"handicapped\":null,\"maritalStatus\":null,\"citizenship\":null,\"ethnicity\":null,\"educationLevel\":null,\"povertyStatus\":null,\"numChildren\":null,\"areFamilyDetailsRequired\":false,\"spouseFatherValue\":null,\"spouseFatherName\":null,\"familyDetails\":null},\"customerAccountSummary\":{\"globalAccountNum\":\"001200000001259\",\"nextDueAmount\":\"2128.0\"},\"clientPerformanceHistory\":{\"loanCycleNumber\":0,\"lastLoanAmount\":\"0.0\",\"noOfActiveLoans\":0,\"delinquentPortfolioAmount\":\"0.0\",\"totalSavingsAmount\":\"1750.0\",\"meetingsAttended\":0,\"meetingsMissed\":0,\"loanCycleCounters\":[],\"delinquentPortfolioAmountInvalid\":false},\"address\":{\"displayAddress\":null,\"city\":\"\",\"state\":\"\",\"zip\":\"\",\"country\":\"\",\"phoneNumber\":\"\"},\"recentCustomerNotes\":[{\"commentDate\":\"2012-06-17\",\"comment\":\"appr\",\"personnelName\":\"New User1244724101456\"}],\"customerFlags\":[],\"loanAccountsInUse\":[{\"globalAccountNum\":\"001200000001262\",\"prdOfferingName\":\"Hawker Loan\",\"accountStateId\":3,\"accountStateName\":\"Application Approved\",\"outstandingBalance\":\"15643.0\",\"totalAmountDue\":\"8977.0\"},{\"globalAccountNum\":\"001200000001279\",\"prdOfferingName\":\"Hazina Micro Loan\",\"accountStateId\":2,\"accountStateName\":\"Application Pending Approval\",\"outstandingBalance\":\"6439.0\",\"totalAmountDue\":\"1716.0\"},{\"globalAccountNum\":\"001200000001280\",\"prdOfferingName\":\"Car Finance\",\"accountStateId\":3,\"accountStateName\":\"Application Approved\",\"outstandingBalance\":\"381.5\",\"totalAmountDue\":\"120.0\"}],\"savingsAccountsInUse\":[{\"globalAccountNum\":\"001200000001260\",\"prdOfferingName\":\"Current Account\",\"accountStateId\":16,\"accountStateName\":\"Active\",\"savingsBalance\":\"1750.0\",\"prdOfferingId\":null}],\"customerMeeting\":{\"meetingSchedule\":\"Recur every 1 Week(s) on Monday\",\"meetingPlace\":\"KINGSTON\"},\"activeSurveys\":false,\"customerSurveys\":[],\"closedLoanAccounts\":[{\"globalAccountNum\":\"001200000001261\",\"prdOfferingName\":\"AUTO LOAN-2\",\"accountStateId\":10,\"accountStateName\":\"Cancel\",\"outstandingBalance\":\"2576.0\",\"totalAmountDue\":\"206.0\"}],\"closedSavingsAccounts\":[]}"}
Don't worry this is just sample data, nothing real here.
Now I require the Customers No, Name, Address, and Savings Account balance. This is the code I've used to parse it:
public CustomerInfo(String jsonTxt) {
try {
JSONObject json = new JSONObject(jsonTxt);
JSONObject customer = json.getJSONObject("CustomerInfo");
custNo = json.getString("globalCustNum");
custName = json.getString("displayName");
address = json.getString("DisplayAddress");
savAcctBal = json.getDouble("totalSavingsAmount");
} catch (final JSONException je) {
je.printStackTrace();
}
}
This of course throws an JSONException. I've learned that the JSON Library may have a few bugs. I've done some tricks, with print statements. It turns out that it likes to consume the 1st element of the JSON string. This heavily screws up going through nested elements like we have here in the example.
Is there an alternative I can use?
Boy, do I want to shoot myself. I figured out my issue before I went to bed. My approach was correct; it was just a matter of me reading the output of Print statements wrong as well as underestimated just how nested the JSON was.
Internally, the JSONOBject class stores the JSON elements, pairs, etc. in a Hashtable. The Hashtable has a side-effect where it will sort the data that's given to it. This of course through off how the JSON was ordered. I figured it was consuming some parts of the JSON, while it really was just putting them to the back...the waaay back if not the end of the JSON. This greatly through me off. I did not realise this until I just ran toString on the Hashtable itself. I then also realise that the JSON was actually more nested than I thought. The four parts I wanted to get, where in 3 different nested JSON objects.
Thus, my solution was to save myself even more grief and just put the JSON through a pretty printer and looked and the structure properly.
Here is my Solution code:
public CustomerInfo(String jsonTxt) {
try {
JSONObject json = new JSONObject(jsonTxt);
JSONObject customer = new JSONObject(json.getString("CustomerInfo"));
JSONObject client = new JSONObject(customer.getString("clientDisplay"));
custNo = client.getString("globalCustNum");
custName = client.getString("displayName");
JSONObject cph = new JSONObject(customer.getString("clientPerformanceHistory"));
JSONObject caddress = new JSONObject(customer.getString("address"));
address = caddress.getString("displayAddress");
savAcctBal = cph.getDouble("totalSavingsAmount");
} catch (final JSONException je) {
je.printStackTrace();
}
}
protip: Always use a Pretty Printer on your JSON, and appreciate it's structure before you do anything. I swear this wont happen to me again.
You can parse the JSON string by the following example
public CustomerInfo(String jsonTxt) {
try {
JSONObject json= (JSONObject) new JSONTokener(jsonTxt).nextValue();
test = (String) json2.get("displayName");
}
catch (JSONException e) {
e.printStackTrace();
}
}