Hi StackOverflow community,
I have a situation where I need to distinct the Java JSONObect key into a List. So that I can do a if else statement after that. Here is an example of my JSON Object.
{
"E23": "1111",
"E25": "5",
"G1": {
"b": "1",
"c": "1"
},
"G2": {
"d": "1"
},
"E2": "test pdf",
"E3": "1",
"E4": "1",
"E5a": "12121991",
"E6": "1",
"E8": "7110",
"E5b": 28,
"E9": "01",
"E1a": "1",
"H3b": "4",
"E24c1": "06",
"E1b": "i",
"H3a": "12",
"E26a": [
"04",
"07",
"09"
],
"E14a": {
"a": "1",
"b": "1",
"c": "1"
}
}
The end result expected is to become like this ArrayList [E,G,H]
Just FYI, the key.chartAt(0) can be from E-I. I am thinking to looping in each of the Object and check the character at 0 and put it in the List if the List doest contain the character yet. But I think its gonna consume a lot of java processing and my function will become longer. Is there any way that I can achieve my end result without looping through all the Object.
Any advise is appreciated.
You can try like this,
JSONObject json = getJsonObject(); // your JSONObject
Set<String> jsonKeys = json.keySet();
Set<Character> myKeySet = jsonKeys.stream()
.map(key-> key.charAt(0))
.collect(Collectors.toSet());
System.out.println(myKeySet);
Output:
[E,G,H]
Note: Since your keys should not be duplicated you use Set, else you can replace it with ArrayList
Related
So, I have the next json:
{
"massive2":[
"a",
"c",
"b"
],
"key5":"val5",
"key2":"val2",
"massive1":[
"3",
"4",
"2",
"1"
],
"key3":"val3",
"key4":"val4",
"key1":"val1"
}
How can I sort all pairs by key and all elements in all massives (to the end of json tree) in alphabetical, or if it is massive in some other order to get json like this:
{
"key1":"val1",
"key2":"val2",
"key3":"val3",
"key4":"val4",
"key5":"val5",
"massive1":[
"1",
"2",
"3",
"4"
],
"massive2":[
"a",
"b",
"c"
]
}
I don't know beforehand how deep my json will be.
Maybe there are some java libraries for this?
let items = {
"massive2":[
"a",
"c",
"b"
],
"key5":"val5",
"key2":"val2",
"massive1":[
"3",
"4",
"2",
"1"
],
"key3":"val3",
"key4":"val4",
"key1":"val1"
};
let data = {};
Object.keys(items).sort().forEach(function(k){
data[k] = items[k];
});
console.log(data);
Im making an app thats dynamic to a json template (the app reads the template from the internet) and i need to read a JSONArray's key string.
my json:
{
"format": {
"Drive": [
"Mecanum",
"Omni",
"Regular"
],
"Drive-Configuration": [
"H",
"X"
],
"Glyph-Elevator": [
"Parallel Elevator",
"Stick Elevator",
"Strip Elevator"
],
"Glyph-Picker": [
"Strip Picker",
"Dual-Servo Picker"
],
"Relic-Elevator": [
"Horizontal Parallel"
],
"Relic-Holder": [
"Pliers",
"Dual-Servo With Rubber Pads"
],
"CypherBox-Fill": [
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12"
],
"Autonomous": [
"Poor",
"Minimal",
"Okay",
"Good",
"Almost Perfect",
"Perfect"
]
}
}
what i want is to read the "Drive" and the "Drive-Configuration" names by code.
what i have:
JSONObject reader=new JSONObject(template);
JSONArray config=reader.getJSONArray("format");
for(int type=0;type<config.length();type++){
JSONArray con=config.getJSONArray(type);
//Here I Want To Read The Array's Name
}
Instead of JSON Parser use GSON.!
add this to your gradle
compile 'com.google.code.gson:gson:2.8.1'
Create a ClassMain.!
class MainClass{
#SerializedName("format")
Value format;
}
Class value{
#SerializedName("Drive")
ArrayList<String> drive;
#SerializedName("Drive-Configuration")
ArrayList<String> driveConfiguration;
generate getter and setter.!
}
and then Convert your JSON to GSON.!
MainClass mainClass= new Gson().fromJson(json.toString(), MainClass.class);
mainClass.getFormat().getDirve();
Used JSONObject.names();
to read the names
ArrayList<Template> tm = new ArrayList<>();
JSONObject reader = new JSONObject(format);
JSONObject config = reader.getJSONObject("format");
Iterator<String> types = config.keys();
while (types.hasNext()) {
String name = types.next();
tm.add(new Template(name, config.getJSONArray(name)));
}
Here's what im trying to do. There are two arrays that i want to retrieve from my mysql database. These two arrays are echoed separately:
echo json_encode(array("friendrequest"=>$friendrequest));
echo json_encode(array("friendresult"=>$friendresult));
This is the code i use to process the resulting string:
public void onResponse(String response) {
Log.d("Response", response);
try {
JSONObject jsonObj = new JSONObject(response);
JSONArray ja_data = jsonObj.getJSONArray("friendresult");
String[] from = {
"first_name",
"anytimer_count",
"relationship_status"
}; //string array
int[] to = {
R.id.textListView1,
R.id.textListView2,
R.id.textListView3
}; //int array of views id's
JSONArrayAdapter arrayListAdapter = new JSONArrayAdapter(MyFriendsActivity.this, ja_data, R.layout.custom_list_items, from, to);
list.setAdapter(arrayListAdapter);
JSONArray ja_requests = jsonObj.getJSONArray("friendrequest");
int ja_lengths = ja_requests.length();
Log.d("Response", Integer.toString(ja_lengths));
} catch (JSONException e) {
Log.e("MyFriendsActivity", "unexpected JSON exception", e);
}
Now, the logged reponse from line 2 in the processing code gives me the following:
Response =
{
"friendrequest": [
{
"first_name": "Tom",
"anytimer_count": "0",
"relationship_status": "0"
},
{
"first_name": "Bert",
"anytimer_count": "0",
"relationship_status": "0"
}
]
}{
"friendresult": [
{
"first_name": "Luuk",
"anytimer_count": "0",
"relationship_status": "1"
}
]
}
This is contains all the values that should be sent and is correct.
The problem is that my processing code is only able to recognize the array that is encoded first in the php script. Basically if i swap the position of the two lines of code in the php script, 'friendrequest' will contain values, while 'friendresult' does not and vice versa. What am i doing wrong here?
The error im getting:
org.json.JSONException: No value for friendresult
at
com.example.tomva.anytimereverywhere.MyFriendsActivity$3.onResponse(MyFriendsActivity.java:84)
Line 84 is the following line:
JSONArray ja_data = jsonObj.getJSONArray("friendresult");
You have to pass yours json in a array to be able to extract them all.
Shold be:
[
<?php
echo json_encode(array("friendrequest"=>$friendrequest));
echo ",";
echo json_encode(array("friendresult"=>$friendresult));
?>
]
Related answer
or you can use following
echo json_encode(array("friendrequest"=>$friendrequest,"friendresult"=>$friendresult));
Replace
echo json_encode(array("friendrequest"=>$friendrequest));
echo json_encode(array("friendresult"=>$friendresult));
With this
echo json_encode(array("friendrequest"=>$friendrequest,"friendresult"=>$friendresult));
Your Response JSON is not valid as it has missing ","
try to change your response from
{"friendrequest": [{"first_name":"Tom","anytimer_count":"0","relationship_status":"0"},{"first_name":"Bert","anytimer_count":"0","relationship_status":"0"}]} {"friendresult": [{"first_name":"Luuk","anytimer_count":"0","relationship_status":"1"}]}
To
[{
"friendrequest": [{
"first_name": "Tom",
"anytimer_count": "0",
"relationship_status": "0"
}, {
"first_name": "Bert",
"anytimer_count": "0",
"relationship_status": "0"
}]
}, {
"friendresult": [{
"first_name": "Luuk",
"anytimer_count": "0",
"relationship_status": "1"
}]
}]
Common Errors
Expecting 'STRING' - You probably have an extra comma at the end of
your collection. Something like { "a": "b", }
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[' -
You probably have an extra comma at the end of your list.
Something like: ["a", "b", ]
Enclosing your collection keys in quotes. Proper format for a
collection is { "key": "value" }
Make sure you follow JSON's syntax properly. For example, always
use double quotes, always quotify your keys, and remove all
callback functions
I'm trying to write a JSON from a java object. Everything works fine until I write the values to a String using the ObjectMapper. The String shows an unexpected field in the JSON document called "map".
I want this:
{
"name": [
{
"a": "1",
"b": "2",
"c": "3",
"d": "4",
"e": "5",
"f": "6"
}
]
}
I get this:
{
"name": [
{
"map": {
"a": "1",
"b": "2",
"c": "3",
"d": "4",
"e": "5",
"f": "6"
}
]
}
This is the class where I've defined the Object I want to convert to JSON:
public class SomeClass{
private List<JSONObject> name;
//getters, setters
}
Can anyone help me?
Please notice that inside the class you are serializing you have a parameter called map if you called it bla you would have seen:
{
"name": [
{
"bla": {
"a": "1",
"b": "2",
"c": "3",
"d": "4",
"e": "5",
"f": "6"
}
]
}
in order to get rid of the parameter name you should use the annotation: #JsonUnwrapped on top of the map parameter inside the class, like:
#JsonUnwrapped
private Map<String, String> map;
Another option is to create a getter function for map use the following:
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(map.getDataMap());
I've solved the problem. I just created an array of object and then I've serialized it with jackson.
private Bla[] bla;
// getters and setters
Class Bla:
private String a;
private String b;
private String c;
...
// getters and setters
Thank you for everything.
Jon
I am using the Wunderground api to get hourly weather forecast for an android app. I want to receive information like Temp and day.
An example of the Json is:
"hourly_forecast": [
{
"FCTTIME": {
"hour": "11","hour_padded": "11","min": "00","min_unpadded": "0","sec": "0","year": "2014","mon": "7","mon_padded": "07","mon_abbrev": "Jul","mday": "8","mday_padded": "08","yday": "188","isdst": "1","epoch": "1404842400","pretty": "11:00 AM PDT on July 08, 2014","civil": "11:00 AM","month_name": "July","month_name_abbrev": "Jul","weekday_name": "Tuesday","weekday_name_night": "Tuesday Night","weekday_name_abbrev": "Tue","weekday_name_unlang": "Tuesday","weekday_name_night_unlang": "Tuesday Night","ampm": "AM","tz": "","age": "","UTCDATE": ""
},
"temp": {"english": "61", "metric": "16"},
"dewpoint": {"english": "56", "metric": "13"},
"condition": "Partly Cloudy",
"icon": "partlycloudy",
"icon_url":"http://icons.wxug.com/i/c/k/partlycloudy.gif",
"fctcode": "2",
"sky": "58",
"wspd": {"english": "7", "metric": "11"},
"wdir": {"dir": "SW", "degrees": "232"},
"wx": "Partly Cloudy",
"uvi": "9",
"humidity": "83",
"windchill": {"english": "-9999", "metric": "-9999"},
"heatindex": {"english": "-9999", "metric": "-9999"},
"feelslike": {"english": "61", "metric": "16"},
"qpf": {"english": "0", "metric": "0"},
"snow": {"english": "0", "metric": "0"},
"pop": "2",
"mslp": {"english": "29.92", "metric": "1013"}
}
It seems to be in an array but when i tried the following it came up with a error of not being a json object.
String row = rootArray.getAsJsonObject().get("sky").getAsString();
** Edit **
I was able to get it to work with the code
String skyText = rootobj.getAsJsonObject().getAsJsonArray("hourly_forecast").get(0).getAsJsonObject().get("sky").getAsString();
with rootobj being my json object
The JSON you posted is not an array. Instead, it is an object with a key named "hourly_forecast" and that key points to a value that is an array.
Key Value
hourly_forecast JSONArray
So if your JSON was in an string called wundergroundData, you'd access the "sky" value like this:
JSONObject json = new JSONObject(wundergroundData);
String skyText = json.getJSONArray("hourly_forecast").get(0).getString("sky");
or, to more closely follow the example you posted, I imagine something like this would work as well:
String row = rootArray.getAsJsonObject().getJSONArray("hourly_forecast").get(0).getString("sky");
Although, you'd probably want to rename the rootArray variable because the root is actually a JSONObject. Not an array.
If this doesn't work, post your FULL JSON and I can tell you exactly what you need to do to work with it. Right now, you're missing either a curly brace or a square brace at the start, as well as the ending of the JSON. I'm assuming here that your JSON starts with a curly brace. If it starts with a square brace then you will need something like the following code instead:
String row = rootArray.get(0).getJSONArray("hourly_forecast").get(0).getString("sky");