Dealing with multiple JSON objects (Android Java) - java

I am currently dealing with some JSON and apparently running into a bit of trouble. I have a PHP page that fetches two unrelated MySQL requests at the same time and displays both of them, one after the other. I have two JSON encodings. My issue is, I can't get my Java program to recognize the second one. First one is parsed fine.
I ran the JSON through an online validator and it is quite clear those two shouldn't follow as they are now. What is the correct way of dealing with those two ?
Please note that the comma between them (line 11) was added manually because I thought it would help. It didn't.
{
"player_update":[
{
"id":"16",
"name":"Phil_TEST",
"last_login":"2015-10-12 00:36:05",
"for_update":"00:00:00",
"newplayer":"no"
}
]
},
{
"player_list":[
{
"id":"16",
"name":"Phil_TEST",
"last_login":"2015-10-12 01:00:42"
},
{
"id":"15",
"name":"Phil8",
"last_login":"2015-10-12 00:50:49"
}
]
}
Edit : here's the code I'm using. I can parse the player_update fine, but nothing is done after I ask to find the the player_list, my Logs stop there. Test 00 AND Test 1 both don't display.
JSONObject obj = new JSONObject(stream);
JSONArray arr_player_update = obj.getJSONArray("player_update");
String newplayer = arr_player_update.getJSONObject(0).getString("newplayer");
Log.i("PhLog LobbyActivity", "Newplayer : "+newplayer);
Log.i("PhLog LobbyActivity", "Test 0");
JSONArray arr_player_list = obj.getJSONArray("player_list");
Log.i("PhLog LobbyActivity", "Test 00");
for (int i = 0; i < arr_player_list.length(); i++) {
String id = arr_player_list.getJSONObject(i).getString("id");
String name = arr_player_list.getJSONObject(i).getString("name");
String last_login = arr_player_list.getJSONObject(i).getString("last_login");
}
My PHP pages consists of : json_encode($array1);echo",";json_encode($array2);
But the comma is useless. Maybe if my JSON was valid then it would work better.
Logcat :
10-12 09:48:00.086 1052-1052/? I/PhLog LobbyActivity: Newplayer : no
10-12 09:48:00.086 1052-1052/? I/PhLog LobbyActivity: Test 0
10-12 09:48:00.086 1052-1052/? W/System.err: org.json.JSONException: No value for player_list

Problem:
The way you are encoding JSON is wrong. That was not an example of valid JSON formatted data. You can check it's validness here.
Solution :
You have two different arrays to send as response. Then combine both of them in single array first and then encode it in json format.
Example: (in your php file)
$data_to_send=array();
$data_to_send['player_update']=$player_update; // an array of player update
$data_to_send['player_list']=$player_list; // an array of player_list
json_encode($data_to_send); // to send the response

Related

How to replace a JSON String with Java?

In my JSON Array inside of its file, it has an array set that goes as follows:
{
"user_interface_fields" : {
"tip_identifier" : {
"uuid": "12345678-1234-1234-1234-123456789112"
}
"insert_time" : "2001-01-01T00:00:00Z"
}
And now I got this file written in java
#Test
public void testExampleMessageToJson() throws Throwable {
log.info("\n\nTesting persist service [message to json]?\n");
//Setup
String rawJson = TestUtils.getResourceMessage("examples/life.json");
String tip_identifier_uuid = "12345678-1234-1234-1234-123456789112";
log.info("Raw Json:\n():", rawJson);
assertTrue(StringUtils.isNotBlank(rawJson));
//Test
JSONObject foundObj = persistService.messageToJson(rawJson);
//Verify
String tip_identifier_time = foundObj.getString("insert_time");
String new_time = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").format(Calendar.getInstance().getTime());
foundObj.put(new_time, foundObj).getString("insert_time");\
assertNotNull(foundObj);
String new_uuid = foundObj.getJSONObject("user_interface_fields").getJSONObject("tip_identifier").getString("uuid");
assertEquals(tip_identifier_uuid , new_uuid);
assertEquals(tip_identifier_time, new_time);
log.info("\n\nTesting persist service [message to json] COMPLETE!\n");
}
My goal is to have life.json's time to be nearly identical to our current time (so like if it's 11/11/21 01:30:21.22, insert_time's data should be around 01:30:21.2234 or whatever and at any time i or any other person runs the code it should be a near match..)
But in my failure trace it tells me:
org.junit.ComparisonFailure: expected:<202[0-02-19'T'00:00:]00> but was:<202[1-11T17:46:46+00]00>
I'm thinking that the logging is messed up because expected should be nearly matched as the current time (as stated in my goal). Since messagetoJson gets the current time and inserts it, when my test pulls out the insert_time it should be a couple of milliseconds behind and so I need to validate that it's within a second or ~1000 milliseconds.
But I don't know what the heck I should do or where I should go from here in order to fix that.

Iterate a JSON Object of Objects Firebase

I'm using firebase4j (a firebase library for Java, I know it is much better to go with node, I just wanted to try to do it with Java). In my database I need to persist the url of images with a bunch of the picture's information. The thing is that the picture url itself is very deep into the JSON
"users" : {
"aCategory" : {
"aUser" : {
"photos" : {
"photoUid1" : [ {
"value1" : false,
"value2" : "qwerty",
"score" : 40,
"url" : "http://someurl.com"
}
That is why I am trying to create an index for the pictures ordered by score, containing the url pointing to the location of the photo object in the firebase database. Here is where the issue begins. Firebase4j does not let you push, to a list for example, so the index ends up with this format:
{
"-UID1": {
"firebaseImgUrl": "users/aCategory/aUser/photos/photoUid1",
"score": 31
},
"-UID2": {
"firebaseImgUrl": "users/aCategory/aUser/photos/photoUid2",
"score": 30
}
}
I already added the rule ".indexOn" in order for firebase to answer with the right photos when asked for http://firebaseurl.com/users/...?orderBy="score"&limitToFirst=10, which is what I'm doing. I would like to know how should I iterate a JSON object of object as shown in the example above. I'm receiving the data from an Angular 4 client. I've tried a number of methods which haven't worked for me:
result: Photo[] = [];
for(let key in json){
console.log(key); //prints the UIDs
console.log(key.url); //url is not a property of string
//thus
result.push(new Photo(key.url, key.score)); //not working
}
The key is only a string, indicating the keys in your json. You should use it to access your object, like this:
result: Photo[] = [];
for(let key in json){
result.push(new Photo(json[key].firebaseImgUrl, json[key].score));
}

Converting JSON Object to table rows Dynamically

I'm now working with API calls currectly, so most the requests are done through ajax call. As you can expect, both the data sent to server and data received from server will be xml data. I've successfully able to dynamically construct the xml data during the sign up process and during post requests. By utilising JaxB, I've done the necessary steps in server.
Now I've to get the data as xml from server if a user needs to view a ceertain resource. Like before, I'm using jaxb to convert Java object into xml data and I'm getting the xml data in success function of Javascript. There are lot of examples and questions present on converting this xml data into user viewable form.
By my main goal is to make every function Dynamic, Consider now I'm going to show the list of users to admin, I can use these examples to convert my xml data into tables.
Display JSON Data in HTML Table
populate jquery data table with returned json data
If I'm doing like that, I've to manually write the same process with some modification based on table fields for every list view. This is a bad practise if I'm going to copy paste the same code with some modifications for 10 list views. I would like to make the xml to table conversion as a common function for any number of tables no matter how many fields are present in it.
I'm getting the xml data from server as String. So I've converted it to recognizable xmlData using following code.
var xmlData = jQuery.parseXML(data); //data is the xml String which I'm getting from server
//Converting xmlData into JSON Objects
var containerTag = myTag //I can get this from - document.getElementById("tableId").name
var output = new Array( );
var rawData = xmlData.getElementsByTagName(containerTag)[0];
var i, j, oneRecord, oneObject;
for (i = 0; i < rawData.childNodes.length; i++) {
if (rawData.childNodes[i].nodeType == 1) {
oneRecord = rawData.childNodes[i];
oneObject = output[output.length] = new Object( );
for (j = 0; j < oneRecord.childNodes.length; j++) {
if (oneRecord.childNodes[j].nodeType == 1) {
oneObject[oneRecord.childNodes[j].tagName] = oneRecord.childNodes[j].firstChild.nodeValue;
}
}
}
}
By displaying the data as console.log(output[0]); , I'm getting my real data. But I searched to use this information to populate it in table, most of them suggests to do it like
.fieldname1
.fieldname2
and so on which is not I'm expecting to. I've been learning Javascript now a days, but I dont know how to make the process common for all tables irrespective of no of fileds.
Note: I'm using jquery datatables.
Just a thought comes up in my head. Is it possible to just give the Json object to jquery datatables and it'll do the remaining process..?
For reference, this is my xml data
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Users>
<user>
<id>1</id>
<username>user1</username>
<email>email1</email>
<status>active</status>
</user>
<user>
<id>2</id>
<username>user2</username>
<email>email2</email>
<status>active</status>
</user>
<user>
<id>3</id>
<username>user3</username>
<email>email3</email>
<status>inactive</status>
</user>
</Users>
This is the Json object
Object { id: "1", username: "user1", email: "email1", status: "active" } //output[0]
Object { id: "2", username: "user2", email: "email2", status: "active" } //output[1]
Object { id: "3", username: "user3", email: "email3", status: "inactive" } //output[2]
As #epascarello said only a cleaner way is to create tr's dinamically based on the output array index and td's based on the keys from the output[i] -json. Using jquery an example should look like this.
var table = $('<table></table>');
for(var i=0; i < output.length; i++) {
var tr = $('<tr></tr>');
for(var key in output[i]) {
var td = $('<td></td>');
td.attr('class', key);
td.text(output[i][key]);
tr.append(td);
}
table.append(tr);
}
$('body').append(table);
Example here: http://jsfiddle.net/atrifan/4zfs57m8/3
you can even try this
var output = [{id: 1, name: 'Alex', phone: '000'}, {id: 2, name: 'Paul', phone: '010'}];
var stBldr='';
stBldr+='<table border=1>';
$.each(output,function(i,v){
stBldr+='<tr>';
stBldr+='<td>'+$(v)[0].id+'</td><td>'+$(v)[0].name+'</td><td>'+$(v)[0].phone+'</td>';
stBldr+='</tr>';
});
stBldr+='</table>';
var str=$(stBldr);
$('body').append(str);
DEMO

JSON parsing. Unexpected character (t) at position 2. JAVA

I'm trying to parse JSON data from a google maps search.
I've tryed both JACKSON and and now I'm Trying JSON SIMPLE. Both of them gives the same error.
First of all I'm doing an search on Google maps.
String urlString = "http://maps.google.com/maps?f=q&source=s_q&output=json&start=0&q="+ "Stockholm" + "+Gym";
Gives me JSON while(1);{title:"stockholm Gym - Google Maps",url:"/maps?f=q\x26source=s_q\x26start=0\x26q=stockholm+Gym\x26ie=UTF8\x26hq=Gym.............. and so on.
I'm replacing the while(1); with ""; before i return the string.
To the problem when I'm trying to parse it
JSONParser parser = new JSONParser();
String jsonString = "";
// UriHandler.mapSearchJson is the method that returns the jsonString.
String jsonData = UriHandler.mapSearchJSON(jsonString);
Object obj = "";
try {
obj = parser.parse(jsonData);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject jsonObj = (JSONObject) obj;
String title = (String) jsonObj.get("title");
System.out.println(title);
This gives me the exception.
Unexpected character (t) at position 2.
When I'm debbuging it. comes all the way to when it's trying to parse the string. then the obj is = null.
What in thw world am I doing wrong.
Thanks!
As the others already mentioned, a nonquoted field name is not standard JSON. However, Jackson (and maybe others) has a set of option settings that allow it to work with nonstandard, but common JSON derivatives:
JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES
will enable processing of unquoted field names.
The response is not valid JSON, as the key name was not quoted with double quotes.
{title:"stockholm Gym"
is invalid JSON, it should be this:
{"title":"stockholm Gym"
Notice how title is surrounded by " double quotes
You are pulling back Javascript code that is meant for the maps.google.com site to use.
There could be any Javascript code in that response, not just the JSON that happens to be returned as part of the search.
You need to request from their maps API instead:
http://maps.googleapis.com/maps/api/geocode/json?address=Stockholm+Gym&sensor=false
This will return you only the JSON data.
Have a look the Google Maps API for more options.
I faced this error when trying to parse the json returned from kafka (kafka twitter producer).
The message returned was including some extra text other than json (KeyedMessage(twitter-test_english,null,null). Because of that I was facing this error.
KeyedMessage(twitter-test_english,null,null,{"created_at":"Sat Apr 23 18:31:10 +0000 2016","id":723942306777337856,"id_str":"723942306777337856"}
Pass only the message part from returned json and convert it into string.
{"created_at":"Sat Apr 23 18:31:10 +0000 2016","id":723942306777337856,"id_str":"723942306777337856"}
message = new KeyedMessage("twitter-test_english", (String)queue.take());
//System.out.println("This is message"+message.message());
String message_string = message.message().toString();
JsonParse.toParseJson(message_string);

When trying to retrieve JSONObject out of JSONArray is returning null?

Im trying to do the following:
UserFunctions uf = new UserFunctions();
JSONArray json = uf.getAllFreebies();
System.out.println(json + "blah1"); //Here im able to retrieve the whole JSONArray.
try{
System.out.println("1");
for (int i = 1; i <json.length(); i++) {
System.out.println("2");
jo = json.optJSONObject(i); //Im getting null value here
System.out.println(jo + "blah2"); //Here im getting null
...}
Im printing out my JSONArray using following lines.
JSONArray json = uf.getAllFreebies();
System.out.println(json + "blah1");
Now on the following lines when i tried to retrieve the JSONObject from the JSONArray and tried to print it out,it prints out "null" instead of the JSONObject at the particular index.
jo = json.optJSONObject(i);
System.out.println(jo + "blah2");
Can anyone pls tell me what am i doing wrong?I mean how can i get a null for JSONOBject when my JSONArray is not null?
Thank You.
Following is my JSONArray logcat:
05-31 21:02:57.156: I/System.out(318): [["viking","Art","Potrait","Potrait","Good","im giving out potrait 7325697","176 Fiat Ave","Iselin","New Jersey","USA","08830","2012-05-27"],["n00b","Books","Novels","Novels","Good","Im giving out novels 7325697","b9 maa krupa","petlad","Gujarat","India","388450","2012-05-27"],["n00b","Computers","laptop","laptop giveaway","Good","Im giving out laptop if you are interested than pls call on 7325697","B9 Ma Krupa","Petlad","Gujarat","India","388450","2012-05-27"],["mista","Cameras & Photos","Camera","Camera GiveAway","Very good","im giving out camera .its kodak .pls email me on mista#gmail.com","Mista Lee elm street","seoul","Korea","South Korea","ha8 9sd","2012-05-27"],["panda","Gaming Consoles","XBOX","XBOX 360","Very Good","Im giving out xbox 360.if you are interested please email me on panda#gmail.com","435 Carmen Rd,","Buffalo","New York","USA","14226","2012-05-27"],["viking","Cameras & Photos","Camera","Kodak Camera","Good","Kodak Camera giveaway.Pls call on 732397","","Iselin","New Jersey","USA","08830","2012-05-28"],["viking","Books","Novels","Novel GA","Good","Novel give away.call on 7325697.","","Iselin","New Jersey","USA","08830","2012-05-28"],["viking","Automotive","Car","Car GiveAway","Good","Im giving out car.if you are interested pls call 7323697.","176 Fiat Ave","Iselin","New Jersey","USA","08830","2012-05-29"],["viking","Collectibles","Medallions","Medallion GA","Very Good","Im giving out medallion.if inetrested pls call 732697","176 Fiat Ave,","Iselin","New Jersey","USA","08830","2012-05-29"],["viking","Clothing & Accessories","cloths","cloths giveaway","Good","im giving out cloths if you are interested pls call on 735697","176 Fiat Ave,","Iselin","New jersey","USA","08830","2012-05-29"],["viking","Books","Novel","Novel GA","Good","pls call 735697","435 carmen rd","buffalo","ny","usa","14226","2012-05-29"],["viking","Books","TextBook","CHemistry 101","GOod","pls call 735697","176 fiat ave","iselin","new jersey","usa","08830","2012-05-29"],["mista","Books","Notebook","Notbook","Good","im giving out notebbok if you are interested pls call 48374288423","elm street","seaoul","na","South Korea","jfjafjk","2012-05-29"]]blah1
logcat output when trying to print out JSONOBject at index i
05-31 21:02:57.156: I/System.out(318): nullblah2
The JSON [[...], [...], [...]] does not contain JSON-objects, but it does have some JSON-arrays.
Thus optJSONObject finds a JSON-array (where it expected a JSON-object) and returns null because it is of the incorrect type. (opt is short for optional.)
Use optJSONArray (note Array and not Object). Alternatively, use getJSONArray, which will throw a JSONException on failure.
Happy coding.
Note that JSON keeps a strict distinction between Objects, Arrays, and the various Values. The concept of an Array being a special (sub)kind of Object (in the JSON sense) exists in JavaScript but does not necessarily extend to other JSON implementations. For instance, the JSONArray class has no relationship with the JSONObject class.

Categories

Resources