I am trying to send an array with a bunch of objects back to android?
I tried String Builder like so:
StringBuilder sb = new StringBuilder();
sb.append("[");
for(int i = 0; i <usersChanged.size(); i++) {
DatabaseUser userChange = usersChanged.get(i);
if(userChange.getIsFollowingType() == 0) {
String userIdStr = "{userId:" + userChange.getUserId() + ",";
String followingStr = "following:" + String.valueOf(userChange.getIsFollowingType())+ "}]";
sb.append(userIdStr).append(followingStr);
but I am doing something wrong here. On my server side I am using node.js and would parse the array if I send over a string no problem, but this is not sending a string version of the array? What do I need to change on my string builder? Or is there a more efficient way to send over the list of usersChanged - (which is List)
I am using retrofit if there is a way to do it easy with that.
Your code will send things like
[{userId: someuserid, following: someparameter}]
You need to have the double quote (" ") sent over as well.
for(int i = 0; i <usersChanged.size(); i++) {
DatabaseUser userChange = usersChanged.get(i);
if(userChange.getIsFollowingType() == 0) {
String userIdStr = "{\"userId\":\"" + userChange.getUserId() + "\",";
String followingStr = "\"following\":\"" + String.valueOf(userChange.getIsFollowingType())+ "\"}]";
sb.append(userIdStr).append(followingStr);
You should also probably move the "]" to after the loop.
EDIT:
Forgot to mention this, but you can definitely use JSONArray and JSONObject to make your life easier.
JSONArray jsonArray = new JSONArray();
for(...){
JSONObject jsonObject = new JSONObject();
jsonObject.put("userId", userChange.getUserId());
jsonObject.put("following", String.valueOf(userChange.getIsFollowingType()));
jsonArray.put(jsonObject);
}
Then send over the jsonArray.
Related
I need to get "examples" data that is an array inside of 'results'
JSON FILE
and append it to a string. What would be the easiest way to do that?
this is how i would get "definitions"
private JSONObject queryResults;
...
...
String finalResults = "";
JSONArray results = queryResults.getJSONArray("results");
for(int i = 0; i < results.length(); i++){
JSONObject item = results.getJSONObject(i);
finalResults += item.getString("definition") + " ";
}
As this topic is related to Android application, the easiest way to get the mentioned value without using any additional libraries is to check if JSONObject inside the for-loop has attribute definitions and get the value as a String.
You can go with it like this
String finalExamples = "";
JSONArray results = queryResults.getJSONArray("results");
for (int i=0; i < results.length(), i++) {
JSONObject item = results.getJSONObject(i);
if (item.has("examples")) {
examples += item.getString("examples");
}
}
I assumed that you don't want to update your result String value if examples is not available in the JSONObject.
If you want to handle other cases, for example when "examples" is available in the object but is null or is set to empty String you can use other methods of JSONObject to check it.
More info about working with JSONObjects you can find in the documentation
I have been working on getting data from JSON API for wordpress from https://wordpress.org/plugins/json-api/other_notes/
I have used the follwing to fetch data. Everything is working fine except that it is taking about 30 seconds to load data on to the tabview.
try {
JSONObject jObj = new JSONObject(result);
int count = (jObj.getInt("count_total"));
JSONArray jArray = jObj.getJSONArray("posts");
// Toast.makeText(getApplicationContext(), "Year: " + date2.substring(0, 4) + "Hour: " + date2.substring(11, 13), Toast.LENGTH_SHORT).show();
// Toast.makeText(getApplicationContext(),"Hour: "+date2.substring(11,13),Toast.LENGTH_SHORT).show();
// Extract data from json and store into ArrayList as class objects
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
JSONArray jArray2 = json_data.getJSONArray("categories");
JSONObject json_data2 = jArray2.getJSONObject(0);
DataFish fishData = new DataFish();
fishData.fishImage = json_data.getString("thumbnail");
fishData.fishName = json_data.optString("title", "N/A");
String comment = json_data.optString("comment_count", "0");
fishData.comment = comment;
//fishData.fishName ="Title";
// fishData.sizeName = json_data.getString("size_name");
String category_array = json_data2.optString("title", "N/A");
fishData.sizeName = category_array;
fishData.price = 10;
fishData.url =
json_data.optString("url", "N/A");
data.add(fishData);
}
}
Any other way to fetch data faster so that user need not wait for awful 25-30 seconds to load data?
you should use the new and highly used library for JSON or xml api integration or data convert library.
// retrofit, gson
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
and also see this link it help you that how to implement or use this
http://www.androidhive.info/2016/05/android-working-with-retrofit-http-library/
I have this code from JSONParser.java
try{
JSONArray postArray = jsonObject.getJSONArray("posts");
// Go through each post
for (int i = 0; i < postArray.length(); i++) {
JSONObject postObject = postArray.getJSONObject(i);
Post post = new Post();
post.setCfs(postObject.getJSONObject("custom_fields").optString("entity", "N/A"));
that displays this
["Some text"]
I want it to display without [" and "]
My Json for that specific part is as below
"posts":[{
"date":"2016-02-10 10:28:42",
"categories":[{}],
"tags":[],
"author":{"name":"admin"},
"custom_fields":{
"ref_number":["ITB NUMBER: ITB\/002\/2016"],
"deadline":["26 February, 2016"],
"entity":["Refugees (xxx)"]
}
It seems that "entity" is array and you should try something like that:
post.setCfs(postObject.getJSONObject("custom_fields").optJSONArray("entity").getString(0));
I want to load JSON data into the List view with subtitle and images (Left side on the row).
Here below I have posted my sample JSON response code :
for (int i = 0; i < contacts.length(); i++) {
JSONObject obj = contacts.getJSONObject(i);
Iterator keys = obj.keys();
while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();
// store key in an arraylist which is A,B,...
// get the value of the dynamic key
JSONArray currentDynamicValue = obj.getJSONArray(currentDynamicKey);
Log.d("Response: ", "> " + currentDynamicKey);
int jsonrraySize = currentDynamicValue.length();
if(jsonrraySize > 0) {
for (int ii = 0; ii < jsonrraySize; ii++) {
JSONObject nameObj = currentDynamicValue.getJSONObject(ii);
String name = nameObj.getString("name");
System.out.print("Name = " + name);
//Log.d("Response: ", "> " + name);
//store name in an arraylist
}
}
}
}
I want to Show Tittle : currentDynamicKey values and Sub Title : Name string values.
If you already have your data and you don't necessarily need to integrate the server requests with your adapter, then you really just need an adapter which supports a JSONArray. There's a really nice open source one within the Advanced-Adapters library. Then it's just a matter of passing the JSONArray to the adapter and setting the adapter to a ListView.
I have a long JSON string representing a string[] array being returned from a WCF service. The array elements are simply strings, they are not objects. This is an example of the return data
["1|ArrayElement1","2|ArrayElement2","3|ArrayElement3"..."n|ArrayElementn"]
I don't mind the index being included in the string, but I need to parse the strings into an ArrayList in Android so that I can adapt it to a ListView.
Since these technically aren't JSONObjects, how can I iterate over them and extract the string from each array element?
this is a valid JSON array of strings, you can parse it normally like this
JSONArray jsonStrings = json.getJSONArray("items");
String strings[] = new String[jsonStrings.length()];
for(int i=0;i<strings.length;i++) {
strings[i] = jsonStrings.getString(i);
}
Maybe this post can help you out:
JSON Array iteration in Android/Java
HashMap<String, String> applicationSettings = new HashMap<String,String>();
for(int i = 0; i < settings.length(); i++){
String value = settings.getJSONObject(i).getString("value");
String name = settings.getJSONObject(i).getString("name");
applicationSettings.put(name, value);
}
JSONArray names= json.names();
JSONArray values = json.toJSONArray(names);
for(int i = 0 ; i < values.length(); i++){
if(names.getString(i).equals("description")){
setDescription(values.getString(i));
}
else if(names.getString(i).equals("expiryDate")){
String dateString = values.getString(i);
setExpiryDate(stringToDateHelper(dateString));
}
else if(names.getString(i).equals("id")){
setId(values.getLong(i));
}
else if(names.getString(i).equals("offerCode")){
setOfferCode(values.getString(i));
}
else if(names.getString(i).equals("startDate")){
String dateString = values.getString(i);
setStartDate(stringToDateHelper(dateString));
}
else if(names.getString(i).equals("title")){
setTitle(values.getString(i));
}
}
Just to clarify, as I understand it you are receiving a JSON array of strings which are strings of valid JSON prefixed with the array index and a pipe character?
First, I would suggest contacting the creator of this abomination and lecturing them on violating standards. If they won't listen, talk to their bosses. This kind of thing is unacceptable in my opinion and needs to stop.
Second, I'd suggest doing something like this:
string[] element_strings = JSON.deserialize(WCF_string_result);
object[] elements = new object[element_strings.length];
for(int x = 0; x < elements.length; x++)
{
int pipeIndex = element_strings.indexOf("|");
elements[x] = JSON.deserialize(element_strings[x].substr(pipeIndex + 1));
}
Of course this assumes you have some kind of method for deserializing strings of JSON objects. If you don't I'd recommend using the built in library available in Android:
http://developer.android.com/reference/org/json/package-summary.html
If you want to extract specific value from it using Java8 stream on JSONArray. Then this code will help.
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.json.JSONArray;
public class JsonArrayTest {
public static void main(String[] args) {
System.out.println("Output - "+ getValue("[{\"id\":\"11\",\"username\":\"ABC\"},{\"id\":\"12\",\"username\":\"ABC\"}]\""));
System.out.println("Output - "+ getValue("[{\"id\":\"13\",\"username\":\"XYZ\"}]\""));
}
private static String getValue(String input) {
JSONArray jsonArray = new JSONArray(input);
return IntStream
.range(0, jsonArray.length()).mapToObj(obj -> jsonArray.getJSONObject(obj))
.filter(filterObj -> filterObj.getString("id") != null && "12".equals(filterObj.getString("id")))
.map(finalObj -> finalObj.getString("username")).collect(Collectors.joining(""));
}
}
Note: This is just an example how can you extract a specific value from JSONArry using stream APIs. You can change the filter condition or drop it according to your requirement.