JSON-Simple. Modify and use complex object - java

I am using the JSON-simple library to parse the Json format. How can I use or modify something to a JSONArray? For e.g. consider the following json
"Place": [
{
"name": "owner 1"
},
{
"name": "owner 2"
}
],
"branch": [
{
"name": "sucursal",
"employe": [
],
"clients": [
]
},
I need to add some clients and in the future modify them. How to achieve this?

Simply create a pojo class in the same format.
Classs Pojo{
private List<Place> place;
private List<Branch> branch;
// other fields
}
and use writeValueAsString() from your object mapper to convet it to json.

Related

GeoJson Jackson - parse JSON to Java object fails

I am working on parsing a GeoJSON file into Java POJO classes.
I have found the GeoJSON Jackson library which seems to be exactly the same as I need.
https://github.com/opendatalab-de/geojson-jackson
I have a JSON like the following:
{
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"properties": {
"lfdNr": 1,
"betriebsNummer": 33,
"nummer": 4,
"bezeichnung": "TERST",
"kng": 61062323,
"nArtCode": "A",
"nArtB": "ACKERLAND",
"flaeche": 4.0748
},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[
15.8867118536754,
48.4004384452486
],
[
15.884483831836,
48.3981983444393
],
[
15.8847389374202,
48.3991957290405
],
[
15.8853143451339,
48.3991585954555
],
[
15.8851662097189,
48.398462039698
],
....
]
]
}
}
]
}
I wish to use it as a FeatureCollection java object:
objectMapper.readValue(json, FeatureCollection.class);
I get the following:
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct
instance of `org.geojson.GeoJsonObject`
(no Creators, like default constructor, exist): abstract types either need to be mapped to concrete types,
have custom deserializer, or contain additional type information
at [Source: (String)"{"type":"FeatureCollection","features":[{"type":"Feature","properties":{"lfdNr":1,"betriebsNummer":10086722,"nummer":4,"bezeichnung":"TERST","fskennung":61062323,"nutzungsArtCode":"A","nutzungsArtBezeichnung":"ACKERLAND","flaeche":4.0748},"geometry":{"type":"Polygon","coordinates":[[[15.8867118536754,48.4004384452486],[15.8829132747878,48.4002081767679],["[truncated 2362 chars]; line: 1, column: 251]
(through reference chain: org.geojson.FeatureCollection["features"]->java.util.ArrayList[0]->org.geojson.Feature["geometry"])
I assume it is because the class Geometry a generic type is:
public abstract class Geometry<T> extends GeoJsonObject
I only operate with Polygons and Points.
Any ides how can I get it working?
Thanks a lot!
You can read this JSON content by
GeoJsonObject object = objectMapper.readValue(json, GeoJsonObject.class);
if (object instanceof FeatureCollection) {
FeatureCollection featureCollection = (FeatureCollection) object;
...
}
Jackson will automatically recognize your JSON example as a FeatureCollection object,
because of the annotations on the GeoJsonObject class:
#JsonTypeInfo(property = "type", use = Id.NAME)
#JsonSubTypes({ #Type(Feature.class), ..., #Type(FeatureCollection.class), ... })
...
public abstract class GeoJsonObject implements Serializable {
...
}

How to create a simple json template to send body data with restassured?

So i am trying to build a json to send data to the body of my restassured request, like this structure here:
{
"id": 1,
"category": {
"id": 1,
"name": "duch"
},
"name": "benny",
"photoUrls": [
"string"
],
"tags": [
{
"id": 0,
"name": "string"
}
],
"status": "available"
}
So it is as simple as to copy this as string to the body of the request and i am done, i don't want that at all.
Is there a framework of sorts to give this structure and to change the data dynamically somehow?
I don't want this: (for example)
given().body("{\r\n\"city\": \"Hod Hasharon\",\r\n\"description\": \"Automation Hotel\",\r\n\"name\":\"Nir Great hotel\",\r\n\"rating\":5\r\n}")
.when().post("http://localhost:8090/example/v1/hotels").then().statusCode(201);
I want to be more flexible here, to reference some kind of object (A template with the option to change the data in some places?) that handles this stuff, is there something like that?
I think what you need is using POJO and Jackson to serialize it to json.
public class Payload {
private int id;
private String name;
private List<Tag> tags; //Tag is another class you need to create the same way
//getters, setters
}
And then using objects as payload in your request:
Payload payload = new Payload();
payload.setId(123);
payload.setName("John");
given().contentType("application/json").body(payload).when().post("http://example.com");
Also don't forget to add jackson-databind dependency to your project.
There's more about that in official documentation here: https://github.com/rest-assured/rest-assured/wiki/Usage#object-mapping

Deserialize polypmorphic JSON types with key-based type names

Here is the sample JSON I want to deserialize with Jackson.
{
"person": {
"contacts": {
"address": {
"type": "Office",
"street": "1600 Amphitheatre Parkway",
"city": "Mountain View",
"state": "CA",
"zip": "94043",
"country": "United States"
},
"email": {
"type": "Home",
"emailAddress": "e.schmidt#google.com"
},
"phone": [
{
"type": "Mobile",
"phoneNumber": "+1 888 555555"
},
{
"type": "Home",
"phoneNumber": "+1 888 1111111"
}
],
"website": {
"type": "work",
"webService": "URL",
"webAddress": "www.google.com"
}
},
"firstName": "Eric",
"lastName": "Schmidt"
}
}
The tricky bit to deserialize here is the contacts node.
Things to note:
contacts is a polymorphic abstract type (see POJOs below)
the type information (e.g., `addresss) is contained as a key in a wrapper
this wrapper can be an object if there is only one value (email, address, website) OR an array if there are multiple (phone)
Target POJOs:
public class Person
{
public String firstName;
public String LastName;
public List<Contact> contacts; // mixes Address, Phone, Email, Website
}
public abstract class Contact {
public Long id;
}
public class Phone extends Contact
{
public String type;
public String phoneNumber;
}
// other subtypes of Contact omitted for brevity
note: external requirements require that I use the abstract Contact type. I would rather deserialize directly to these POJOs rather than having an intermediate Contacts POJO that the contact types hang off of and them manual mapping/converting to my List in another step.
I've looked over many other jackson + polymorphic deserialization questions, but none seem to handle this case (#2 and #3 in particular).
I want to deserialize the contacts object to a List<Contact>.
What is proper application of #JsonTypeInfo and #JsonSubTypes needed to achieve this?
(if anyone is interested this is CapsuleCRM's JSON format)
You'll need to write a custom deserializer and register it with Jackson. The implementation would check for initial start then parse accordingly. Think sax style processing.

gson model for array

I have a JSON file like following:
{
"count": 60,
"value": [{
"changesetId": 60,
"url": "http://...",
"author": {
"id": "...",
"displayName": "*...",
"uniqueName": "...",
"url": "http://...*
"imageUrl": "http://..."
},
"checkedInBy": {
"id": "...",
"displayName": "...",
"uniqueName": "...",
"url": "http://...",
"imageUrl": "http://..."
},
"createdDate": "2016-11-08T22:05:11.17Z",
"comment": "..."
},
I am stuck at the point to create a model to use the API Gson. I started like:
public class Changesets{
int count;
*TODO* // model for the JSON above.
}
A start for the model or the entire model would be much appreciated. I will use this to deserialize.
Edit: I tried;
public class Changesets {
int count;
int changeset;
String url;
Changeset.Author author;
Changeset.CheckedInBy checkedInBy;
String createdDate;
String comment;
}
Where I could successfully write Changeset model.
If you really need to model the respective Java classes, you will need to reverse engineering the JSON structure.
In your case it will be something like this:
public class Changesets{
int count;
List<Change> value;
}
and I will let you complete the work.
However, if you only need an ad hoc Java object to deal with a complex JSON object in which you are only interested in a very specific property value, you can use the solution I suggested in this answer:
Dynamic JSON structure to Java structure

How to handle List<String> in Realm?

I have tried add the JSON response into the Realm database. I handled the response through GSON and then tried to convert to realm. I have already extended RealmObject for my response model class. I am also using RealmString class for handling List by using RealmList. But when I tried to GSON to Realm object I get errors. I am looking for an example of this kind if anyone has one. All support are appreciated. Below is my JSON response.
{
"transactionType": 12,
"location": {
"type": "Point",
"coordinates": [
77.7,
12.9
]
},
"rooms": {
"bedrooms": {
"total": 2,
"metadata": [
{
"name": "bedroom 2",
"images": [
"Eshant",
"Abhijeet"
]
}
]
}
}
}
I answered a very similar question here https://stackoverflow.com/a/39993141/1666063
Here is short walkthrough how to to JSON -> GSON -> Realm:
Use http://www.jsonschema2pojo.org/ to generate a POJO with getters and setters for GSON
for the classes and subclasses you want to store in Realm add extends RealmObject to them
for all your classes that extends RealmObject make sure to put #PrimaryKey on of the fields (like an ID)
replace any usage of List<Foo> with RealmList<Foo>
Foo MUST extends RealmObject as well (even if it is a String)
Add a TypeAdapter to GSON that can handle RealmList(here is one I wrote that takes a generic T)

Categories

Resources