I have a dictionary on a website in form of json which looks for example like this:
"types":[{
"id":"0",
"name":"value1"
},{
"id":"1",
"name":"value2"
},{
"id":"2",
"name":"value3"
}]
I cant find any useful example of a method that could help me retrieve that information and put it in, for example, a string array.
Maybe anyone of you come across same problem please help!
P.S. I tried method like simplest way to read json from a URL in java with no success.
It is array of json object value whose key is types. You can use json-java library like gson, jackson,flexjson etc.. to parse this json object and achieve your required result.
GSON Example -
JsonElement jElement = new JsonParser().parse(jsonString);
JsonObject jObject = jElement.getAsJsonObject();
jObject = jObject.getAsJsonObject("types");
Or you can use pojo class like -
public class Type {
private int id;
private String name;
...
}
gson.fromJson(jsonString, Type.class);
Refer java docs.
Related
I am getting String jsonObject in my controller.
The structure is following:
{
"name":"name",
"schema": {
...
...
}
}
I need to parse it into a Plain Old Java Object and receive schema as a String (saving the structure). When I am using System.out.print("schema"), I expect to see:
{
...
...
}
I have a POJO Collection with String name and Object schema fields.
I am using GSON to get Collection.class from String json:
new Gson().fromJson(json, Collection.class);
When I try to print Collection.schema I get the following output:
{......} - in a one row.
I really need to get this object as a String without formatting
This should work. Basically, you hydrate your Collection object and then just send your schema back through Gson. Done.
Gson gson = new Gson();
Collection collection = gson.fromJson(json, Collection.class);
String schema = gson.toJson(collection.getSchema());
System.out.println(schema);
Question could be asked as to why you are accepting a String from your controller? Perhaps you can get the framework you are using to pass in a fully converted Collection object and save yourself a step?
Also, for your Collection.schema, it's common to use Map<String, Object> instead of Object for this type of "schema"-less type of paradigm.
I tried converting my json string to java object by using Gson but somehow it was not successful and I haven't figured out why..
My Json string
{
"JS":{
"JS0":{
"Name":"ABC",
"ID":"5"
},
"JS1":{
"Location":"UK",
"Town":"LD"
},
"JS2":{
"Usable":"true",
"Port":"ABC"
}
}
}
In java code I have 4 classes, JS, JS0, JS1 and JS2
JS class contains JS0, JS1 and JS2 variables
JS0, JS1 and JS2 classes contain fields as in Json string example, e.g. JS0 contains 02 fields, String Name and String ID
In all classes I have getter/setter for variables, 02 constructors (01 with empty parameters and another one with all variables in the parameter field)
And for using Gson:
Gson gson = new Gson();
jsObject = gson.fromJson(sb.toString(), JS.class);
When I access JS0, JS1 and JS2 objects from jsObject, they are null...
Can someone show me what did I do wrong?
Thank you very much,
The problem here is, you are trying to convert
{
"JS" : {
/* rest of JSON */
}
}
to JS object, but the above JSON is a representation of Java class like this
class Foo {
JS JS;
}
So, you need to get the value of JS from the JSON string first, then call fromJSON to deserialize it with the JS.class passed as the second parameter.
OR
Create a simple class containing only JS as a variable, then call fromJSON with that class passed as the second parameter of fromJSON like this:
Java
class Foo {
JS JS;
}
jsObject = gson.fromJson(sb.toString(), Foo.class);
I am trying to parse the JSON from this link: https://api.guildwars2.com/v2/items/56 , everything fine until i met the line: "infix_upgrade":{"attributes":[{"attribute":"Power","modifier":4},{"attribute":"Precision","modifier":3}]} ...
If i dont get this wrong: infix_upgradehas 1 element attributes inside him. attributes has 2 elements with 2 other inside them. Is this a 2 dimension array?
I have tried (code too long to post):
JsonObject _detailsObject = _rootObject.get("details").getAsJsonObject();
JsonObject infix_upgradeObject = _detailsObject.get("infix_upgrade").getAsJsonObject();
JsonElement _infix_upgrade_attributesElement = infix_upgradeObject.get("attributes");
JsonArray _infix_upgrade_attributesJsonArray = _infix_upgrade_attributesElement.getAsJsonArray();
The problem is that I dont know what to do next, also tried to continue transforming JsonArray into string array like this:
Type _listType = new TypeToken<List<String>>() {}.getType();
List<String> _details_infusion_slotsStringArray = new Gson().fromJson(_infix_upgrade_attributesJsonArray, _listType);
but im getting java.lang.IllegalStateException: Expected STRING but was BEGIN_OBJECT which i guess comes from the attributes...
With a proper formatting (JSONLint, for example, checks if the JSON data is valid and does the formatting, which makes the structure more clear than what the GW link gives), attributes looks actually like this:
"attributes": [
{
"attribute": "Power",
"modifier": 4
},
{
"attribute": "Precision",
"modifier": 3
}
]
So it's an array of JsonObject and each object as two key-value pairs. This is why the parser throws an error because you require that this array contains only String which is not the case.
So the actual type is:
Type _listType = new TypeToken<List<JsonObject>>(){}.getType();
The problem is that I dont know what to do next
Hold on. You are using Gson and Java is an OO language so I suggest you to create classes.
This would be easier for you to fetch the datas afterward and for the parsing since you just need to provide the class of the actual class the JSON data represents to the parser (some edge-cases could be handled by writing a custom serializer/deserializer).
The data is also better typed than this bunch of JsonObject/JsonArray/etc.
This will give you a good starting point:
class Equipment {
private String name;
private String description;
...
#SerializedName("game_types")
private List<String> gameTypes;
...
private Details details;
...
}
class Details {
...
#SerializedName("infix_upgrade")
private InfixUpgrade infixUpgrade;
...
}
class InfixUpgrade {
private List<Attribute> attributes;
...
}
class Attribute {
private String attribute;
private int modifier;
...
}
and then just give the type to the parser:
Equipment equipment = new Gson().fromJson(jsonString, Equipment.class);
Hope it helps! :)
Given the following JSON object
{
"id": 5,
"data: { ... }
}
Is it possible to map this to the following POJO?
class MyEntity {
int id;
Map<String, Object> data;
}
Because I would like to leave the data object open ended. Is this even possible or what is a better approach to go about this? I am doing this on Android.
I don't have any idea about Android application but you can achieve it using Gson library easily.
The JSON that is used in your post is not valid. It might be a typo. Please validate it here on JSONLint - The JSON Validator
Simply use Gson#fromJson(String, Class) method to convert a JSON string into the object of passed class type.
Remember the name of instance member must be exactly same (case-sensitive) as defined in JSON string as well. Read more about JSON Field Naming
Use GsonBuilder#setPrettyPrinting() that configures Gson to output Json that fits in a page for pretty printing.
Sample code:
String json = "{\"id\": 5,\"data\": {}}";
MyEntity myEntity = new Gson().fromJson(json, MyEntity.class);
String prettyJsonString = new GsonBuilder().setPrettyPrinting().create().toJson(myEntity);
System.out.println(prettyJsonString);
output:
{
"id": 5,
"data": {}
}
I have checked out many pages but most of the tutorials and script return an error code with this type of JSON output. So how would I be able to extract the data from this JSON in Java?:
[
{
"user":{"id":"1","username":"user1"},
"item_name":"item1",
"custom_field":"custom1"
},
{
"user":{"id":"2","username":"user2"},
"item_name":"item2",
"custom_field":"custom2"
},
{
"user":{"id":"3","username":"user3"},
"item_name":"item3",
"custom_field":"custom3"
}
]
If you want to use Gson, then first you declare classes for holding each element and sub elements:
public class MyUser {
public String id;
public String username;
}
public class MyElement {
public MyUser user;
public String item_name;
public String custom_field;
}
Then you declare an array of the outermost element (because in your case the JSON object is a JSON array), and assign it:
MyElement[] data = gson.fromJson (myJSONString, MyElement[].class);
Then you simply access the elements of data.
The important thing to remember is that the names and types of the attributes you declare should match the ones in the JSON string. e.g. "id", "item_name" etc.
If your trying to serialize/deserialize json in Java I would recommend using Jackson. http://jackson.codehaus.org/
Once you have Jackson downloaded you can deserialize the json strings to an object which matches the objects in JSON.
Jackson provides annotations that can be attached to your class which make deserialization pretty simple.
You could try JSON Simple
http://code.google.com/p/json-simple/
Example:
JSONParser jsonParser = new JSONParser();
JSONArray jsonArray = (JSONArray) jsonParser.parse(jsonDataString);
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject obj = (JSONObject) jsonArray.get(i);
//Access data with obj.get("item_name")
}
Just be careful to check for nulls/be careful with casting and such.