create JSONArray in php and send it to android - java

i'm developing an android project which i need to create a JSON message in my php server and send it to the android devices.
i wrote the following code in php
$event_array = array();
// fill the event_array with some data
print json_encode(array('event_array' => $event_array));
but the result is like
{
"event_array": {
"id_1": {
"name": "name",
"logo_address": "logo_address",
"title": "title",
"time": null,
"address": null,
"address_location": null,
"explain": null,
"type": null,
"id": "id_1",
"number_of_users": null
},
"id_2": {
"name": "name2",
"logo_address": null,
"title": null,
"time": null,
"address": null,
"address_location": null,
"explain": null,
"type": null,
"id": "id_2",
"number_of_users": null
}
}
}
and it's not a json array and i get exception in my android code which simply is
JSONObject jObject = new JSONObject(res);
JSONArray jArray = jObject.getJSONArray("event_array");
what's wrong?
thanks for any help

{ means object, [ means array.
In your case its two objects.
JSONObject jObject = new JSONObject(res);
is correct and contains another object called event_array.
JSONObject jsonEvents = new JSONObject(jObject.getString("event_array"));
while jsonEvents now holds
jsonEvents.getString("id_1");
which is another jsonObject.
If you want to output as array, use array again.
As written in http://de3.php.net/json_encode it must be something like this to get an array
echo json_encode(array(array('event_array' => $event_array)));
So it means it should be like this to match your case.
echo json_encode(
array(
'event_array' =>
array(
array("id_1" => array('name' => 'name', 'logo_...' => '...')),
array("id_2" => array('name' => '....', 'logo_....' => '....'))
)
));
to read this in Java its more likely
JSONObject json = new JSONObject(data);
JSONArray jsonArr = json.getString('event_array');
for (int i = 0; i <= jsonArr.length(); i++) {
JSONObject jsonEventData = jsonArr.getJsonObject(i);
}

Related

Java: Array of Arrays from JSON

I have a JSON Arrays of Array like this
"results": [
{
"id": "AAA",
"color": "#4D4837",
"links": {
"self": "https://aaa.com",
"html": "https://bbb.com",
"download": "https://ccc.com",
"download_location": "ddd.com"
},
"categories": [],
"likes": 3891,
},
{
"id": "BBB",
"color": "#4D453",
"links": {
"self": "https://abb.com",
"html": "https://bcc.com",
"download": "https://ccc.com",
"download_location": "ddd.com"
},
"categories": [],
"likes": 3000,
}
]
And I would like to retrieve "https://bbb.com" and "https://bcc.com" of "html", but I don't know how to do that.
Based on kindly comment, I put the following.
somehow, "getJSONObject()"can not be put. The error message says "Cannot resolve method 'getJSONObject' in 'JSONArray'".
JSONArray array = new JSONArray((Collection) jobjt.get("Strings"));
for (int i =0 ; i<2 ; i++){
JSONObject job = (JSONObject) array.get(i); --> get(i) can not be changed to getJSONObject(i)
String id = job.get("id").toString();
String color = job.get("color").toString();
String photoUrl = job.get("links").toString(); --> By updating here, I want to store only "https://bbb.com" and "https://bcc.com".
}
But when I tried to use the following, not only "html", but "self" and the other information are retrieved.
String photoUrl = job.get("links").toString();
Please tell me how to retrieve only "html".
I am using IntelliJ.
Steps to be followed(assuming you have proper JSONArray you mentioned):
get JSONObject from your JSONArray by index ie. for your case, index=0 here
Get the inner JSONObject by key of links
Now, access your content by key of html
Example for your case:
JSONObject indexedObject = jsonArray.getJSONObject(0);
JSONObject linksObject = indexedObject.getJSONObject("links");
String html= linksObject.getString("html");
Better keep checking if key exists as Harshal suggests

Get Value from JSON into Map, then value out of the Map

I have the following JSON data:
JSON:
[{
"valInternalCode": "NE",
"valMinimumInputString": "NE",
"valExternalRepresentation": "Northeast",
"valActionCode1": "1",
"valActionCode2": null,
"valActionCode3": null,
"valActionCode4": null,
"id": {
"valcodeId": "X.LOCATION",
"pos": 1
},
"uniqueId": "X.LOCATION-1",
"caption": "Northeast"
}, {
"valInternalCode": "NW",
"valMinimumInputString": "NW",
"valExternalRepresentation": "Northwest",
"valActionCode1": "1",
"valActionCode2": null,
"valActionCode3": null,
"valActionCode4": null,
"id": {
"valcodeId": "X.LOCATION",
"pos": 2
},
"uniqueId": "X.LOCATION-2",
"caption": "Northwest"
}
I am able to parse it and create a Map from the data like so:
Gson gson = new Gson();
Type collectionType = new TypeToken<Collection<Map>>(){}.getType();
Collection<Map> dataCollection = gson.fromJson(jsonString.toString(), collectionType);
I can then iterate through it and get a value that I need using the Key like so:
iterator.next().get("valInternalCode");
What I am struggling with is how to get something that is inside of the id field:
"id": {
"valcodeId": "X.LOCATION",
"pos": 2
},
I am using Hibernate to get the data from a non normalized Oracle database (that is why hibernate creates the id field the way it does)
EDIT:
My attempt at an ugly way of doing it. Basically looping within the loop:
while (valIterator.hasNext()) {
Map currentVal = valIterator.next();
String valId = "";
Collection<Map> idVal = (Collection<Map>) currentVal.get("id");
Iterator<Map> valIdIterator = idVal.iterator();
while (valIdIterator.hasNext()) {
Map valIdCurrentVal = valIdIterator.next();
valId = valIdCurrentVal.get("valcodeId").toString();
}
}
Getting a ClassCastException when I try to cast currentVal.get("id") to a Collection

Add new content to JSON-File

i have a json-file called "user.json". Now i want to add a new user. I know how to get the content of the file and put it in a String, but i dont know how to add new content correctly. "jsonString" is the content of "user.json"
JSONParser parser = new JSONParser();
Object object = parser.parse(jsonString);
JSONObject jsonObject = (JSONObject) object;
jsonObject.put("name", name);
jsonObject.put("region", region);
jsonObject.put("v1", v1);
jsonObject.put("v2", v2);
System.out.println(jsonObject.toJSONString());
The output is:
{
"v1": false,
"v2": false,
"name": "test",
"region": "",
"user": [
{
"v1": "true",
"v2": "true",
"name": "UserName",
"region": ""
}
]
}
But it should be:
{
"user": [
{
"v1": "true",
"v2": "true",
"name": "UserName",
"region": ""
},
{
"v1": false,
"v2": false,
"name": "test",
"region": ""
}
]
}
Does somebody know how to do it right?
I looked it up but all the examples are not working for me, because when i try
JSONObject object = new JSONObject(jsonString);
or
JSONArray array = new JSONArray(jsonString);
i always get "the constructor ist undefined".
Edit:
content of user.json
{"user":[
{"name":"Testuser1", "region":"A", "v1":"false", "v2":"false"},
{"name":"Testuser2", "region":"B", "v1":"true", "v2":"true"},
{"name":"Testuser3", "region":"B", "v1":"false", "v2":"false"},
{"name":"Testuser4", "region":"A", "v1":"true", "v2":"true"},
{"name":"Testuser5", "region":"A", "v1":"false", "v2":"false"}
]}
Edit2:
I solved the problem
Object object = parser.parse(new FileReader(classLoader.getResource("user.json").getFile()));
JSONObject jsonObject = (JSONObject) object;
JSONArray array = (JSONArray) jsonObject.get("user");
JSONObject newObject = new JSONObject();
newObject.put("name", name);
newObject.put("region", region);
newObject.put("v1", v1);
newObject.put("v2", v2);
array.add(newObject);
Map<String, JSONArray> map = new HashMap<>();
map.put("\"user\"", array);
String mapInhalt = map.toString();
if (mapInhalt.contains("=")) {
System.out.println("yop");
mapInhalt.replaceFirst("=", ":");
}
System.out.println(mapInhalt);
it seems you are adding fields to your jsonObject, and what you want to do it basically adding the new object to the inner json array (in this case field is called "user"
try this:
JSONObject newObject=new JSONObject();
newObject.put("name", name);
newObject.put("region", region);
newObject.put("v1", v1);
newObject.put("v2", v2);
jsonObject.getJSONArray("user").add(newObject)
you can use fromObject() method:
JSONObject json = JSONObject.fromObject(jsonStr);
JSONArray jsonArry = JSONArray.fromObject(jsonStr);

Accessing json string in java and creating hashmap Android

I have a JSON string and I am trying to retrieve information from it. Json String looks like this.
JSON STRING :
{
"information": {
"device": {
"id": 0
},
"user": {
"id": 0
},
"data": [
{
"datum": {
"id": "00GF001",
"history_id": "9992BH",
"name": "abc",
"marks": 57,
"class": "B",
"type": "Student"
}
},
{
"datum": {
"id": "72BA9585",
"history_id": "78NAH2",
"name": "ndnmanet",
"marks": 70,
"class": "B",
"type": "Student"
}
},
{
"datum": {
"id": "69AHH85",
"history_id": "NN00E3006",
"name": "kit",
"department": "EF003",
"class": "A",
"type": "Employee"
}
},
{
"datum": {
"id": "09HL543",
"history_id": "34QWFTA",
"name": "jeff",
"department": "BH004",
"class": "A1",
"type": "Employee_HR"
}
}
]
}
}
I am trying to access data JSONArray and respective Datum from it. I differentiated each datum as per type such as student, employee etc and push information in hashmap.
I successfully did it in javascript but in Java I am struggle abit.
When I am trying to access JSONArray it throws exception
try {
JSONObject data = new JSONObject(dataInfo);
// Log.d(TAG, "CHECK"+data.toString());
JSONObject info = data.optJSONObject("information");
if(info.getJSONArray("data").getString(0).equals("Student") > 0) //exception here
Log.d(TAG, "Data"+ data.getJSONArray("data").length()); //exception here too
for(int m = 0; m < data.length(); m++){
// for(int s = 0; s < data[m].ge)
}
} catch (JSONException j){
j.printStackTrace();
}
Any pointers to create hashmap respective type I have. Appreciated
If you're trying to access the type field of a datum object, you'll want something like this:
JSONObject data = new JSONObject(dataInfo); // get the entire JSON into an object
JSONObject info = data.getJSONObject("information"); // get the 'information' object
JSONArray dataArray = info.getJSONArray("data"); // get the 'data' array
for (int i = 0; i < dataArray.length(); i++) {
// foreach element in the 'data' array
JSONObject dataObj = dataArray.getJSONObject(i); // get the object from the array
JSONObject datum = dataObj.getJSONObject("datum"); // get the 'datum' object
String type = datum.getString("type"); // get the 'type' string
if ("Student".equals(type)) {
// do your processing for 'Student' here
}
}
Note that you'll have to deal with exception handling, bad data, etc. This code just shows you the basics of how to get at the data that you're looking for. I separated each individual step into its own line of code so that I could clearly comment what is happening at each step, but you could combine some of the steps into a single line of code if that is easier for you.
if dataInfo is the json you posted, then you have to access information and from information, you can access data:
JSONObject data = new JSONObject(dataInfo);
JSONObject info = data.optJSONObject("information");
if (info != null) {
JSONArray dataArray = info.optJSONArray("data")
}

Parsing Json in Android and set it in a ListView

In my android project, I have the string text which got the following data:
[
{
"admin": true,
"created_at": "2012-10-16T07:26:49Z",
"email": "asdf#gmail.com",
"id": 28,
"language": "fr",
"name": "Marc",
"profile_pic_content_type": null,
"profile_pic_file_name": null,
"profile_pic_file_size": null,
"profile_pic_updated_at": null,
"provider": null
},
{
"admin": false,
"created_at": "2013-04-02T18:47:36Z",
"email": "asdf2#gmail.com",
"id": 263,
"language": "en",
"name": "Marcus",
"profile_pic_content_type": null,
"profile_pic_file_name": null,
"profile_pic_file_size": null,
"profile_pic_updated_at": null,
"provider": null
}
]
I converted it into a json object thanks to this:
JSONObject jsonObj = new JSONObject(text);
I want to parse that Json object, and setting it inside a ListView, but even with the official documentation I can't succeed in doing so.
After parsing, I want to keep only the first part of the array, and delete every field excepting the email, language and name, to get this in the end:
[
{
"email": "asdf#gmail.com",
"language": "fr",
"name": "Marc"
}
]
You're dealing with a JSONArray - the [ ] - that contains two separate JSONObject. The way you extract values from this structure is simply to go piece by piece, first getting the nested objects from the array and then extracting their internal values. You can then repackage it as you wish. For example:
int numObject = jsonArray.length();
JSONArray repackArray = new JSONArray();
for(int i = 0; i < numObject; i++){
JSONObject nested = jsonArray.getJsonObject(i);
//get values you need
String email = nested.getString("email");
String language = nested.getString("language");
String name = nested.getString("name");
//add values to new object
JSONObject repack = new JSONObject();
repack.put("email", email);
repack.put("language", language);
repack.name("name", name);
//add to new array
repackArray.put(repack);
}
Alternatively if put doesn't work for you, you can always create your own String in JSON format and then simply create a new JSONObject using that string as an argument in the constructor. I assumed you were working with a JSONArray in the above example. If you're starting with a JSONObject the process is the same. Just get the JSONArray out of the object first before unpacking.

Categories

Resources