Add to a list based on property in an object - java

private static CodeList prepareChangeObject(CodeList codeList, CodeList existingCodeList, boolean dataExists)
throws EntityValidationException {
CodeList UpdatedCodeList = new CodeList();
BeanUtils.copyProperties(codeList, UpdatedCodeList);
Set<CodeListData> updatedDataList =UpdatedCodeList.getData().stream().collect(Collectors.toSet());
updatedDataList.addAll(existingCodeList.getData());
List<CodeListData> finalData = updatedDataList.stream().collect(
collectingAndThen(toCollection(() -> new TreeSet<>(comparing(CodeListData::getKey))), ArrayList::new));
finalData = finalData.stream().filter(data -> {
if (data.getOperation() == null)
data.setOperation(MetaConstants.OPERATION_ADD);
if (null != data.getOperation()) {
if (data.getOperation().equals(MetaConstants.OPERATION_DELETE) && dataExists)
exceptionMessagesList.add(
new ExceptionMessage("foundation.OperationNotAllowed", new String[] { data.getKey() }));
if (data.getOperation().equals(MetaConstants.OPERATION_DELETE) && !dataExists)
return false;
if (data.getOperation().equals(MetaConstants.OPERATION_ADD))
return true;
}
return false;
}).collect(Collectors.toList());
UpdatedCodeList.setData(finalData);
if(!CollectionUtils.isEmpty(exceptionMessagesList))
throw new EntityValidationException(HTTPClientError.BAD_REQUEST, exceptionMessagesList);
return UpdatedCodeList;
}
1.The above method should return a change object based on the operation specified.
public static void main(String[] args) throws JsonMappingException, JsonProcessingException, EntityValidationException {
String jsonPost = "{\n"
+ " \"id\": \"temperature101\",\n"
+ " \"descriptions\": [\n"
+ " {\n"
+ " \"languageCode\": \"en\",\n"
+ " \"description\": \"description\",\n"
+ " \"longDescription\": \"long description\"\n"
+ " },\n"
+ " {\n"
+ " \"languageCode\": \"de\",\n"
+ " \"description\": \"description\",\n"
+ " \"longDescription\": \"long description\"\n"
+ " }\n"
+ " ],\n"
+ " \"dataType\": \"String\",\n"
+ " \"data\": [\n"
+ " {\n"
+ " \"key\": \"val1\",\n"
+ " \"value\": \"High\"\n"
+ " },\n"
+ " {\n"
+ " \"key\": \"val4\",\n"
+ " \"value\": \"Medium\"\n"
+ " },\n"
+ " {\n"
+ " \"key\": \"val3\",\n"
+ " \"value\": \"Low\"\n"
+ " }\n"
+ " ]\n"
+ "}";
String jsonPatch = "{\n"
+ " \"id\": \"temperature101\",\n"
+ " \"descriptions\": [\n"
+ " {\n"
+ " \"languageCode\": \"en\",\n"
+ " \"description\": \"description1\",\n"
+ " \"longDescription\": \"long description1\"\n"
+ " },\n"
+ " {\n"
+ " \"languageCode\": \"de\",\n"
+ " \"description\": \"description1\",\n"
+ " \"longDescription\": \"long description1\"\n"
+ " }\n"
+ " ],\n"
+ " \"dataType\": \"String\",\n"
+ " \"data\": [\n"
+ " {\n"
+ " \"key\": \"val1\",\n"
+ " \"value\": \"High\",\n"
+ " \"operation\": \"DELETE\"\n"
+ "\n"
+ " },\n"
+ " {\n"
+ " \"key\": \"val4\",\n"
+ " \"value\": \"Medium\",\n"
+ " \"operation\": \"DELETE\"\n"
+ " }\n"
+ " ]\n"
+ "}";
ObjectMapper mapper = new ObjectMapper();
CodeList ExistingodeList = mapper.readValue(jsonPost, CodeList.class);
CodeList currentCodeList = mapper.readValue(jsonPatch, CodeList.class);
CodeList upDatetedCodeList = prepareChangeObject(currentCodeList, ExistingodeList, false);
Gson gson = new Gson();
System.out.println(upDatetedCodeList.toString());
System.out.println(gson.toJson(upDatetedCodeList));
}
the above main method to test the code
#Data
public class CodeListData {
#Column("ID")
#JsonIgnore
private String id;
#Column("KEY")
private String key;
#Column("VALUE")
private String value;
#Column("ETAG")
#JsonIgnore
private String etag;
#JsonIgnore
#Column("VERSION")
#Version
private Long version;
#Transient
#JsonProperty(access = Access.WRITE_ONLY)
private String operation;
}
Pojo for reference
#Data
public class CodeList implements Persistable<String>{
#NotNull
#Id
#Column("ID")
private String id;
#MappedCollection(idColumn = "ID", keyColumn = "ID_SEQ")
private List<CodeListDescriptions> descriptions = new ArrayList<>();
#Column("DATA_TYPE")
private String dataType;
#Column("LENGTH")
private String length;
#MappedCollection(idColumn = "ID", keyColumn = "ID_SEQ")
private List<CodeListData> data = new ArrayList<CodeListData>();
#JsonIgnore
#Column("VERSION")
private Long version;
#Column("ETAG")
#JsonIgnore
private String etag;
#Transient
#JsonIgnore
#Setter
private boolean isInsert;
#JsonIgnore
public boolean isNew() {
return isInsert;
}
}
4.codeList pojo
#Data
public class CodeListDescriptions{
#Column("ISO")
public String languageCode;
#Column("DESCRIPTION")
public String description;
#Column("LONG_DESCRIPTION")
public String longDescription;
#Column("ID")
#JsonIgnore
private String id;
}
5.final output required is only "val3" to be present. The method is supposed to remove or add based on the operations DELETE or ADD. The issue is that val4 is still in the output because when the finalData is created it prefers to keep the "val4" from existing data which does not contain any operation. The final output needs to contain the added values and values not specified in the payload but exists in the first one.

it prefers to keep the val4 from existing data which does not contain any operation
you are defaulting to the add operation with this code, so regardless of whether or not there is an operation, you explicitly set one
if (data.getOperation() == null)
data.setOperation(MetaConstants.OPERATION_ADD);
Then you check it like
if (null != data.getOperation()) { // this is always true, because you use the default one line before
...
if (data.getOperation().equals(MetaConstants.OPERATION_ADD))
return true;
}
so in the end the final
return false;
will never be reached.

You create a Set<CodeListData> from both the existing and the update data set. CodeListData defines its equals and hashCode methods over all fields. Note that Lombok ignores transient fields, but those a different from fields annotated with #Transient. So you have val4 twice in the Set once with DELETE operation and once without any operation. The one with DELETE will get filtered out, but the one with no operation will default to ADD and stay in the SET.
Note: I consider it unfortunate to name a variable of type Set anything that ends in List.

Related

com.fasterxml.jackson.databind.exc.MismatchedInputException while read the json string and map to model object

I am trying to read the json String and map to the model object (BusinessModel). The model object is as shown below which has property "List<LookupData> lookupData;" and LookupData is the inner class of BusinessModel class and from jsonString i want to map the LookupData .
Below is the sample model class.
import java.io.IOException;
import java.util.List;
#Getter
#Setter
#EqualsAndHashCode
#NoArgsConstructor
#AllArgsConstructor
#Builder
#JsonIgnoreProperties
public class BusinessModel {
private List<LookupData> lookupData;
#Getter
#Setter
#EqualsAndHashCode
#NoArgsConstructor
#AllArgsConstructor
#Builder
public static class LoanDescLookup {
private String id;
private String description;
private boolean status;
private String type;
}
#Getter
#Setter
#EqualsAndHashCode
#NoArgsConstructor
#AllArgsConstructor
#Builder
public static class LookupData {
private String id;
private String description;
private boolean defaultLookup;
private String regex;
private String regexDescription;
}
}
Below is the sample json String.
String jsonString = "[\n" +
" {\n" +
" \"id\": \"101\",\n" +
" \"description\": \"issueID 101\",\n" +
" \"defaultLookup\": true,\n" +
" \"regex\": \"^([a-zA-Z0-9_-]){4,5}$\",\n" +
" \"regexDescription\": \"A four or five character string, including numbers\"\n" +
" },\n" +
" {\n" +
" \"id\": \"102\",\n" +
" \"description\": \"issueID 102\",\n" +
" \"defaultLookup\": false,\n" +
" \"regex\": \"^([a-zA-Z0-9_-]){4}$\",\n" +
" \"regexDescription\": \"A four character string, including numbers\"\n" +
" },\n" +
" {\n" +
" \"id\": \"103\",\n" +
" \"description\": \"issueID 103\",\n" +
" \"defaultLookup\": false,\n" +
" \"regex\": \"^[A-Z0-9]{11}$\",\n" +
" \"regexDescription\": \"A 11 character vin number\"\n" +
" },\n" +
" {\n" +
" \"id\": \"104\",\n" +
" \"description\": \"issueID 104\",\n" +
" \"defaultLookup\": true,\n" +
" \"regex\": \"^[0-9]{6}$\",\n" +
" \"regexDescription\": \"A 6 character vin number (e.g. 202108)\"\n" +
" }\n" +
" ]";
Sample java code to read the above jsonString and map to model object.
ObjectMapper om = new ObjectMapper();
BusinessModel lookupData = om.readValue(jsonString, BusinessModel.class);
for (int i = 0; i < lookupData.getLookupData().size(); i++) {
BusinessModel.LookupData selectByLookup = lookupData.getLookupData().get(i);
String id = selectByLookup.getId();
String description = selectByLookup.getDescription();
String regex = selectByLookup.getRegex();
String regexDescription = selectByLookup.getRegexDescription();
result.add(BusinessModel.selectByLookup.builder().id(id)
.description(description)
.defaultLookup(result.size() == 0)
.regex(regex)
.regexDescription(regexDescription)
.build());
}
Below is the exception i'm getting while running the above code.
Exception :: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `com.model.BusinessModel` out of START_ARRAY token
at [Source: (String)"[

java - replace string in JSON with json array of objects

I've a JSON:
{
"payment_intent": {
"amount": "Amount",
"currency_code": "840",
"invoice_number": "pay-automation-invoice-no-01",
"payment_intent_id": "pay-automation-return-intent-id-01",
"intent_reference_id": "pay-automation-intent-reference-id-01"
},
"payment_refundable_intents": {
"transactions": {
"sales": "pay-automation-sales"
}
}
}
Now, when I tried to replace string "pay-automation-sales" with JSONArray using
payloadJson = payloadJson.replaceAll("pay-automation-sales", salesString);
salesString is
[{"amount":"200.0","payment_intent_id":"29518150","tender_type":"cash","reference_id":"db79893a-9fe0-4391-91f8-fbc-cash-6c88-66db","intent_reference_id":"db79893a-9fe0-4391-91f8-fbc7945ce446","id":"000000893275","status":"Approved"},{"amount":"800.0","payment_intent_id":"29518150","tender_type":"cash","reference_id":"db79893a-9fe0-4391-91f8-fbc-cash-1d12-8466","intent_reference_id":"db79893a-9fe0-4391-91f8-fbc7945ce446","id":"000000893282","status":"Approved"}]
Here, payloadJson is of type String. The replaceAll works fine but actually I want to pass "sales" as an array of object in JSON. But it is getting passed like this and it's not a valid JSON format. Double quotes in value of sales key in JSON causes an issue I think.
"sales": "[{"amount":"200.0","payment_intent_id":"29518150","tender_type":"cash","reference_id":"db79893a-9fe0-4391-91f8-fbc-cash-6c88-66db","intent_reference_id":"db79893a-9fe0-4391-91f8-fbc7945ce446","id":"000000893275","status":"Approved"},{"amount":"800.0","payment_intent_id":"29518150","tender_type":"cash","reference_id":"db79893a-9fe0-4391-91f8-fbc-cash-1d12-8466","intent_reference_id":"db79893a-9fe0-4391-91f8-fbc7945ce446","id":"000000893282","status":"Approved"}]"
How do I replace string in JSON with valid JSON array of objects?
Since you're working with String objects here and not some form of JSON object model, when you did
payloadJson = payloadJson.replaceAll("pay-automation-sales", salesString);
it found the string
pay-automation-sales
within payloadJson and replaced it verbatin with the contents of salesString. Notice that you did NOT tell it to include the quotes in the original string in the part being replaced.
It should be
payloadJson = payloadJson.replaceAll("\"pay-automation-sales\"", salesString);
You would probably be better off using a real JSON library that understands JSON syntax and can manipulate the JSON as an in-memory document model.
Using Java String
public class StringDemo {
static final String originalJson = " {\n"
+ " \"payment_intent\": {\n"
+ " \"amount\": \"Amount\",\n"
+ " \"currency_code\": \"840\",\n"
+ " \"invoice_number\": \"pay-automation-invoice-no-01\",\n"
+ " \"payment_intent_id\": \"pay-automation-return-intent-id-01\",\n"
+ " \"intent_reference_id\": \"pay-automation-intent-reference-id-01\"\n"
+ " },\n"
+ " \"payment_refundable_intents\": {\n"
+ " \"transactions\": {\n"
+ " \"sales\": \"pay-automation-sales\"\n"
+ " }\n"
+ " }\n"
+ "}";
static final String originalArray = "[{\"amount\":\"200.0\",\"payment_intent_id\":\"29518150\",\"tender_type\":\"cash\",\"reference_id\":\"db79893a-9fe0-4391-91f8-fbc-cash-6c88-66db\",\"intent_reference_id\":\"db79893a-9fe0-4391-91f8-fbc7945ce446\",\"id\":\"000000893275\",\"status\":\"Approved\"},{\"amount\":\"800.0\",\"payment_intent_id\":\"29518150\",\"tender_type\":\"cash\",\"reference_id\":\"db79893a-9fe0-4391-91f8-fbc-cash-1d12-8466\",\"intent_reference_id\":\"db79893a-9fe0-4391-91f8-fbc7945ce446\",\"id\":\"000000893282\",\"status\":\"Approved\"}]";
public static void main(String[] args) {
String editedJson = originalJson.replaceAll("\"pay-automation-sales\"", originalArray);
System.out.println(editedJson);;
}
}
Using Jackson
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.node.*;
public class JacksonDemo {
static final String originalJson = " {\n"
+ " \"payment_intent\": {\n"
+ " \"amount\": \"Amount\",\n"
+ " \"currency_code\": \"840\",\n"
+ " \"invoice_number\": \"pay-automation-invoice-no-01\",\n"
+ " \"payment_intent_id\": \"pay-automation-return-intent-id-01\",\n"
+ " \"intent_reference_id\": \"pay-automation-intent-reference-id-01\"\n"
+ " },\n"
+ " \"payment_refundable_intents\": {\n"
+ " \"transactions\": {\n"
+ " \"sales\": \"pay-automation-sales\"\n"
+ " }\n"
+ " }\n"
+ "}";
static final String originalArray = "[{\"amount\":\"200.0\",\"payment_intent_id\":\"29518150\",\"tender_type\":\"cash\",\"reference_id\":\"db79893a-9fe0-4391-91f8-fbc-cash-6c88-66db\",\"intent_reference_id\":\"db79893a-9fe0-4391-91f8-fbc7945ce446\",\"id\":\"000000893275\",\"status\":\"Approved\"},{\"amount\":\"800.0\",\"payment_intent_id\":\"29518150\",\"tender_type\":\"cash\",\"reference_id\":\"db79893a-9fe0-4391-91f8-fbc-cash-1d12-8466\",\"intent_reference_id\":\"db79893a-9fe0-4391-91f8-fbc7945ce446\",\"id\":\"000000893282\",\"status\":\"Approved\"}]";
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(originalJson);
JsonNode array = mapper.readTree(originalArray);
ObjectNode transactions = (ObjectNode) root.findValue("transactions");
transactions.set("sales", array);
String editedJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(root);
System.out.println(editedJson);;
}
}

List of Json records

I have a list of json records, for instance:
[{“age”:27,”lastname”:”Robert “,”firstName”:”Rob”,”company”:”abc”},
{“age”:27,”lastname”:”Ashok “,”firstName”:”Bob”,”company”:”def”},
{“age”:27,”lastname”:”murali“,”firstName”:”Got”,”company”,”Ghori”}]
Write a method which takes lastName as parameter and based on that input I need to get only that particular record out and get it displayed
Your probleme is not well explained, you can try this solution (after correcting your string to be a real json content)
Using ObjectMapper you can read your string to transform it to an ArrayNode
public static void main(String[] args) throws IOException {
String json= "[\n" +
" {\n" +
" \"age\":27,\n" +
" \"lastname\":\"Robert \",\n" +
" \"firstName\":\"Rob\",\n" +
" \"company\":\"abc\"\n" +
" },\n" +
" {\n" +
" \"age\":27,\n" +
" \"lastname\":\"Ashok \",\n" +
" \"firstName\":\"Bob\",\n" +
" \"company\":\"def\"\n" +
" },\n" +
" {\n" +
" \"age\":27,\n" +
" \"lastname\":\"murali\",\n" +
" \"firstName\":\"Got\",\n" +
" \"company\":\"\"\n" +
" }\n" +
"]";
// example with murali
getLine(json, "murali");
}
private static String getLine(String json, String lastName) throws IOException {
ArrayNode rootNode = (ArrayNode) new ObjectMapper().readTree(json);
for(JsonNode jsonNode : rootNode) {
ObjectNode node = (ObjectNode)jsonNode;
String lastNameValue = node.get("lastname").textValue();
if(lastName.equals(lastNameValue)){
return jsonNode.toString();
}
}
return null;
}
the result for this example is :
{"age":27,"lastname":"murali","firstName":"Got","company":""}

How can I parse JSON Array Using Retrofit and GSON?

I have learnend how to parsing JSON objects via Retrofit Gson but I need to parse a full JSON array via Retrofit Gson.
I need to parse the following :
"{\n" +
" \"snappedPoints\": [\n" +
" {\n" +
" \"location\": {\n" +
" \"latitude\": -35.2784167,\n" +
" \"longitude\": 149.1294692\n" +
" },\n" +
" \"originalIndex\": 0,\n" +
" \"placeId\": \"ChIJoR7CemhNFmsRQB9QbW7qABM\"\n" +
" },\n" +
" {\n" +
" \"location\": {\n" +
" \"latitude\": -35.280321693840129,\n" +
" \"longitude\": 149.12908274880189\n" +
" },\n" +
" \"originalIndex\": 1,\n" +
" \"placeId\": \"ChIJiy6YT2hNFmsRkHZAbW7qABM\"\n" +
" },\n" +
" {\n" +
" \"location\": {\n" +
" \"latitude\": -35.280960897210818,\n" +
" \"longitude\": 149.1293250692261\n" +
" },\n" +
" \"originalIndex\": 2,\n" +
" \"placeId\": \"ChIJW9R7smlNFmsRMH1AbW7qABM\"\n" +
" },\n" +
" {\n" +
" \"location\": {\n" +
" \"latitude\": -35.28142839817933,\n" +
" \"longitude\": 149.1298619971291\n" +
" },\n" +
" \"originalIndex\": 3,\n" +
" \"placeId\": \"ChIJy8c0r2lNFmsRQEZUbW7qABM\"\n" +
" },\n" +
" {\n" +
" \"location\": {\n" +
" \"latitude\": -35.28193988170618,\n" +
" \"longitude\": 149.13001013387623\n" +
" },\n" +
" \"originalIndex\": 4,\n" +
" \"placeId\": \"ChIJ58xCoGlNFmsRUEZUbW7qABM\"\n" +
" },\n" +
" {\n" +
" \"location\": {\n" +
" \"latitude\": -35.282819705480151,\n" +
" \"longitude\": 149.1295597114644\n" +
" },\n" +
" \"originalIndex\": 5,\n" +
" \"placeId\": \"ChIJabjuhGlNFmsREIxAbW7qABM\"\n" +
" },\n" +
" {\n" +
" \"location\": {\n" +
" \"latitude\": -35.283139388422363,\n" +
" \"longitude\": 149.12895618087012\n" +
" },\n" +
" \"originalIndex\": 6,\n" +
" \"placeId\": \"ChIJ1Wi6I2pNFmsRQL9GbW7qABM\"\n" +
" },\n" +
" {\n" +
" \"location\": {\n" +
" \"latitude\": -35.284728724835304,\n" +
" \"longitude\": 149.12835061713685\n" +
" },\n" +
" \"originalIndex\": 7,\n" +
" \"placeId\": \"ChIJW5JAZmpNFmsRegG0-Jc80sM\"\n" +
" }\n" +
" ]\n" +
"}"
I need the lat and longs only.
Here is the method I know to parse JSON Objects via Retrofit GSON
package com.example.akshay.retrofitgson;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
/**
* Created by Akshay on 9/6/2015.
*/
public class gitmodel {
#SerializedName("latitude")
#Expose
public String latitude;
#SerializedName("longitude")
#Expose
public String longitude;
public void setLatitude(String latitude)
{
this.latitude = latitude;
}
public String getLatitude()
{
return latitude;
}
public void setLongitude(String longitude)
{
this.longitude = longitude;
}
public String getlatitude()
{
return latitude;
}
}
You might need the lat/longs only, but the easiest thing to do is to just set up your POJO to get everything, then extract the lat longs from the POJO. You can even design the deserialized object to hide the inner object if you want. In the case of your JSON, this is quite easy, just do this:
public static class SnappedPoints {
private List<Point> snappedPoints;
public String toString() {
return snappedPoints.toString();
}
}
public static class Point {
private Location location;
public double getLatitude() {
return location.getLatitude();
}
public double getLongitude() {
return location.getLongitude();
}
public String toString() {
return "{" + location.getLatitude() + "," + location.getLongitude() + "}";
}
}
public static class Location {
double latitude;
double longitude;
public double getLatitude() {
return latitude;
}
public double getLongitude() {
return longitude;
}
}
You can see this in action by simply doing this:
public static void main(String[] args) {
System.out.println(new Gson().fromJson(json, SnappedPoints.class));
}
Or, in the case of Retrofit, something like this:
public interface MyRetrofitAPI {
#GET("/path/to/json")
void getSnappedPoints(/* arguments */, Callback<SnappedPoints> callback);
}
Retrofit uses the Gson library to serialise Json responses. As long as you have a model class setup correctly, you can tell Gson to try and serialise the json into an instance of that model class. Your code should look something like the following:
String json; // retrieved from file/server
MyObject myObject = new Gson().fromJson(json, MyObject.class)

Parse Youtube JSONC with GSON

i know how to parse Json in android. but i can't seem to wrap my head around parsing JSONC from Youtube using GSON. i just need to parse the title of the video. Thanks here is the url
http://gdata.youtube.com/feeds/api/videos/iS1g8G_njx8?v=2&alt=jsonc
The following code works to parse the given response with Gson
public class ExampleParser {
public static final String JSONC =
"{\"apiVersion\":\"2.1\","
+ " \"data\":{"
+ " \"id\":\"iS1g8G_njx8\","
+ " \"uploaded\":\"2014-05-30T20:00:01.000Z\","
+ " \"updated\":\"2014-11-26T14:14:11.000Z\","
+ " \"uploader\":\"arianagrandevevo\","
+ " \"category\":\"Music\","
+ " \"title\":\"Ariana Grande - Problem ft. Iggy Azalea\","
+ " \"description\":\"Ariana Grande ft. Iggy Azalea - Problem\nBuy now! http://smarturl.it/ArianaMyEvrythnDlxiT?IQid=vevo.cta.problem\nGoogle Play: http://goo.gl/n7rey5\n\nPre-order My Everything and get access to the iHeartRadio Concert video stream where Ariana performs songs from her new album FOR THE FIRST TIME!\nhttp://myplay.me/19ys\","
+ " \"thumbnail\":{"
+ " \"sqDefault\":\"http://i.ytimg.com/vi/iS1g8G_njx8/default.jpg\","
+ " \"hqDefault\":\"http://i.ytimg.com/vi/iS1g8G_njx8/hqdefault.jpg\"},"
+ " \"player\":{"
+ " \"default\":\"http://www.youtube.com/watch?v=iS1g8G_njx8&feature=youtube_gdata_player\"},"
+ " \"content\":{"
+ " \"5\":\"http://www.youtube.com/v/iS1g8G_njx8?version=3&f=videos&app=youtube_gdata\"},"
+ " \"duration\":208,"
+ " \"aspectRatio\":\"widescreen\","
+ " \"rating\":4.731269,"
+ " \"likeCount\":\"1527921\","
+ " \"ratingCount\":1637964,"
+ " \"viewCount\":307368910,"
+ " \"favoriteCount\":0,"
+ " \"commentCount\":156682,"
+ " \"status\":{"
+ " \"value\":\"restricted\","
+ " \"reason\":\"limitedSyndication\"},"
+ " \"restrictions\":["
+ " {\"type\":\"country\","
+ " \"relationship\":\"deny\","
+ " \"countries\":\"DE\"}],"
+ " \"accessControl\":{"
+ " \"comment\":\"allowed\","
+ " \"commentVote\":\"allowed\","
+ " \"videoRespond\":\"moderated\","
+ " \"rate\":\"allowed\","
+ " \"embed\":\"allowed\","
+ " \"list\":\"allowed\","
+ " \"autoPlay\":\"allowed\","
+ " \"syndicate\":\"allowed\"}}}";
public static void main(String[] args) {
Gson gson = new GsonBuilder()
// Add your date deserializer
.create();
YoutubeResponse response = gson.fromJson(JSONC, YoutubeResponse.class);
System.out.println(response);
}
public static class YoutubeResponse {
Double apiVersion;
Data data;
}
public static class Data {
String id;
String uploaded; // TODO should be a date
String updated; // TODO should be a date
String uploader;
String category;
String title;
String description;
Thumbnail thumbnail;
Player player;
Integer duration;
String aspectRatio;
Double rating;
Integer likeCount;
Integer ratingCount;
Integer viewCount;
Integer favoriteCount;
Integer commentCount;
Status status;
List<Restriction> restrictions;
}
public static class Thumbnail {
String sqDefault;
String hqDefault;
}
public static class Player {
#SerializedName("default")
String defaultt; // default is a reserved java keyword
}
public static class Status {
String value;
String reason;
}
public static class Restriction {
String type;
String relationship;
String countries;
}
public static class AccessControl {
String comment;
String commentVote;
String videoRespond;
String rate;
String embed;
String list;
String autoPlay;
String syndicate;
}
}

Categories

Resources