Create a JSON without a key - java

We wanted to create a JSON structure as below in Java
{
[
{
"key": "ABC001",
"value": true
},
{
"key": "ABD12",
"value": false
},
{
"key": "ABC002",
"value": true
},
]
}
To implement this we created a class and had a list private property inside it.
But that is creating a key values
class Response{
private List<Property> values;
// setter getter for this private property
}
The output for this is
{
values : [
{
"key": "ABC001",
"value": true
},
......
]
Is there a way we create the array without the key and inside the { }?

Unfortunately, what you're trying to build is not a valid json.
You can try to validate it here.
With this "json", for example, it would be impossible to read the array, because it has no key.
{
"foo_key" : "bar",
[
{
"key": "ABC001",
"value": true
},
{
"key": "ABD12",
"value": false
},
{
"key": "ABC002",
"value": true
},
]
}
Parsing a json like this one, you could get "bar" because it has a key ("foo_key"), but how could you get the array?
The code you're using is already correct for a valid json.

So, for some reason you want an invalid json, which is an array contained between {}s. Here's how you can do it (I'll assume you use google-gson to make and parse jsons, since you didn't include your code):
// example of the creation of the list
List<Property> values = new ArrayList<>();
values.add(new Property("ABC001", true));
values.add(new Property("ABD12", false));
values.add(new Property("ABC002", true));
//
Gson gson = new Gson();
String json = gson.toJson(values, new TypeToken<List<Property>>() {}.getType());
json = "{" + json + "}";// gotta do what you gotta do...

Related

Get keys from multiple JSON objects

I have a JSON object that contains undetermined pattern and I need to get all keys of the json object and the sub-objects.
Here's an example of a JSON file:
{
"users": {
"address": [
{
"rue": "ruetest",
"postal": 1111
},
{
"rue": "ruetest",
"postal": 2222
}
],
"type": "string",
"user": [
{
"argent": 122,
"id": 1,
"nom": "user1",
"prenom": "last1"
},
{
"argent": 200,
"id": 2,
"nom": "user2",
"prenom": "last2"
},
{
"argent": 1205,
"id": 3,
"nom": "user3",
"prenom": "last3"
}
]
}
}
and I need to have output like this:
[users,type,address,user,argent,id,nom,prenom] or something like this
I don't think there's really a built-in way to do this, but you could achieve your goal by making a function that does it. Something like (in pseudocode):
public Set getJsonKeys(JSON json) {
Set s = new Set();
for (Entry e : json.entrySet()) {
s.add(e.key);
if (e.value instanceof JSON) s.addAll(getJsonKeys(e.value));
}
return s;
}
I chose a Set rather than List to prevent duplicate entries. If you want to include keys of lists just add a check if e.value is a list and if so, iterate over elements and add getJsonKeys(element) for all elements.
Have you tried the Genson Java Collections mode?
It would give you easy generic access to arbitrary JSON files in java.
If you use the fastjson framework, I think you can use the following code to get all the keys:
JSONObject jsonObject = new JSONObject(jsonData);
Iterator keys = jsonObject.keys();
while (keys.hasNext()){
String key = String.valueOf(keys.next());
}

How would I access this key within a JSON object in Java?

I've been having some problems iterating through a JSON object in Java.
Specifically, I'd like to save each value for "name" to the string array "nameList". I've looked up how to do this, and I haven't found a way for this situation.
String[] nameList = new String[]{};
{
"data": {
"Narray": {
"0":
{
"_id": "001",
"name": "studio",
"date": "02141992"
},
"1":
{
"_id": "002",
"name": "venue",
"date": "09041999"
}
}
}
Ideally you'd want Narray to be an actual JSON array, enclosed in [], with each element being another object, containing the property you need, like this:
{
"Narray": [
{
"_id": "001",
"name": "studio",
"date": "02141992"
},
{
"_id": "002",
"name": "venue",
"date": "09041999"
}
]
}
Then you can use jackson to decode the JSON string into a POJO structure. Once you have the objects, you can iterate over the array and retrieve the property you need into a list.
I assume that you only want to save each value of name into a String[] (string array), so you don't need to deserialize the JSON string to POJO, just use basic API to achieve what you want as follows:
BTW, your JSON string is invalid, you miss a right bracket.
ObjectMapper mapper = new ObjectMapper();
JsonNode nArray = mapper.readTree(jsonStr).get("data").get("Narray");
String[] nameList = new String[nArray.size()];
for (int i = 0; i < nArray.size(); i++) {
nameList[i] = nArray.get(String.valueOf(i)).get("name").asText();
}
System.out.println(Arrays.toString(nameList));
Console output:
[studio, venue]

What point of same properites at that json?

When I get this json at POST method I need create a object. But I can't see what I need do exactly with this code. Why there is a lot of same properties? Are they a object of different class in fields class?or what? If they are why not like that host:{ "value":"120.515.151.124"}. Could someone help or show some documents about that?
{
"fields": [
{
"name": "host",
"value": "102.164.152.128"
},
{
"name": "port",
"value": "8564"
},
{
"name": "accessKey",
"value":
"(here is a 64 bit a key like(531b8e6c...)"
},
{
"name": "secretKey",
"value":
"(also here is a 64 bit a key like(531b8e6c...)"
}
]
}
fields is an array of key value pairs.. So, this object will contain a fields object, which is a map. Can you try like this..
public class MyClass {
Map<String, String> fields;
}

Create POJO from json generated by key=>value Array

I want create a pojo from a json like this
{
"1": [
{
"idmapel": 1,
"label": "Fisika"
},
{
"idmapel": 2,
"label": "Kimia"
},
{
"idmapel": 3,
"label": "Biologi"
},
{
"idmapel": 4,
"label": "Matematika"
},
],
"2":[
{
"idmapel": 1,
"label": "Fisika"
}
]
}
when i generate from http://www.jsonschema2pojo.org/ it created a 1 and 2 class, but imagine if i have more than 2 keys. i want to be able to access element by something like this ObjectClass::getList(1) or ObjectClass::getList(2)
You can use a Map to do this.
Map<String, List<Pojo>> map = deserialize(jsonSring);
where Pojo is the class which has fields idmapel and label, deserialize is a method which deserializes the json to object and jsonString is the json string value to deserialize. Then you can access lists with keys
List<Pojo> list1 = map.get("1");
List<Pojo> list2 = map.get("2");

JSON different objects in an array

At the moment i'm trying to understand json and how it works.
But i have a problem with an array of objects.
all objects in the array have a key called "value" (i know it's weird, it's not my code) what also is an object.
And now to the problem: This object called "value" has always different key-values.
So i dont now how i can parse the json code to java object code, when it differ, every time.
Here some examples:
First object of the array:
"value":
{
"local":
[
"English", "Deutsch", Espanol"
],
"english":
[
"English", "Deutsch", Espanol"
],
},
Second object(now a string, not object) of the array:
"value" : "",
Third object of the array:
"value" : {},
...
Maybe I'm doing the parsing wrong.
First I have created the beans classes in java for the json code and then I'm using the automatic parser of google. (gson)
It works when only one of the examples above is inside the json code. (it should not differ, like changing from string to object...)
Gson gson = new Gson();
Output output = gson.fromJson(json, Output.class);
Output is the main class for the json stuff.
I have found out that maybe while parsing I could check a value called "id" first, and from that I could create another beans class with the right variables ...
Thats the code i need to parse to java objects and how do you do that??
The problem is the key called "value", because its always different.
With my method of using the google parser "gson" it wont work, because i'm getting exception that its an string but i was waiting for an object...
{
"status":"success",
"data":{
"panel":{
"title":{
"label":{ "local":"Tote Selection", "english":"Tote Selection" },
"image":"public/img/pick.jpg", "type":"default"
},
"isFirst":false, // currently not used
"isLast":false, // currently not used
"ownCount":0, // currently not used
"panelsCount":0, // currently not used
"elements":[
{
"type":"text",
"id":"1", "value":{ "local":"Scan next order tote",
"english":"Scan next order tote" },
"label":{ "local":"", "english":"" }, "color":"000000",
"fontsize":18, "fontstyle":"flat", "alignment":"left",
"rows":"undefined", "bgcolor":"", "isFocus":false
},
{
"type":"text",
"id":"4", "value":{ "local":"Scan tote: ", "english":"Scan tote: " },
"label":{ "local":"", "english":"" }, "color":"000000", "fontsize":20,
"fontstyle":"strong", "alignment":"left", "rows":"undefined",
"bgcolor":"", "isFocus":false
},
{
"type":"input",
"id":"6", "value":"", "label":{ "local":"", "english":"" },
"color":"000000", "fontsize":24, "fontstyle":"flat", "alignment":"left",
"rows":"undefined", "isFocus":true
},
{
"type":"button",
"id":"1", "value":{ "local":"", "english":"" },
"label":{ "local":"Menu", "english":"Menu" }, "color":"000000",
"fontsize":14, "fontstyle":"strong", "alignment":"left",
"rows":"undefined", "isFocus":false
},
{
"type":"button",
"id":"4", "value":{ "local":"", "english":"" },
"label":{ "local":"Enter", "english":"Enter" }, "color":"000000",
"fontsize":14, "fontstyle":"strong", "alignment":"right",18
"rows":"undefined", "isFocus":false
}
]
},
"authToken":"0fdd440a-619f-4936-ab74-d189accb5bd9",
"routing":{
"controller":"panel",
"action":"process",
"workflowId":"singlepicking",
"taskId":"orderSelection"
}
}
}
Thank you for your help!
it looks a little bit different but your answer helped me! Thx
JsonParser parser = new JsonParser();
JsonObject obj = parser.parse(br).getAsJsonObject();
//now getting all the json values
String status = obj.get("status").getAsString();
JsonObject data = obj.getAsJsonObject("data");
String authToken = data.get("authToken").getAsString();
JsonObject routing = data.getAsJsonObject("routing");
String controller = routing.get("controller").getAsString();
String action = routing.get("action").getAsString();
String workflowId = routing.get("taskId").getAsString();
If I understood ur question properly u can retrieve the values of the JSONArray as below
for (int i = 0; i < JArray.length(); i++) {
print(JArray.getJSONObject(i).tostring())
}
So if i am right u are getting the JSON from a String First?? so please try below first store the String in JSONObject as JSONObject obj = new JSONObject(str);//str is the string that u are getting
to get the valueenglish that are in data-panel-tittle-label is
String englishinLable=obj .getJSONObject("data").getJSONObject("panel").getJSONObject("title").getJSONObject("label").optString("english")

Categories

Resources