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;
}
}
Related
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.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have code that has several classes with different cars and some classes. Below is my code, I'm not sure why vanClass van; is not working as it is basically a copy paste of the past classes that work. Any help is appreciated. To clarify, I am only having problems with the last few lines of the autopark class where I initiate vanClass as van and go from there.
import java.util.*;
class sedan {
String make;
String model;
String color;
int year;
double price;
boolean fourWD;
boolean isheavyDuty;
String carries;
public sedan(String initMake, String initModel, String initColor, int initYear, double initPrice) {
make = initMake;
model = initModel;
color = initColor;
year = initYear;
price = initPrice;
}
#Override
public String toString() {
String name = "Sedan";
String main = (color + " " + make + " " + model + " " + name + " (" + year + ") costs $" + price);
return main;
}
}
class SUV {
String make;
String model;
String color;
int year;
double price;
boolean fourWD;
String carries;
public SUV(String initMake, String initModel, String initColor, int initYear, double initPrice, boolean initFourWD){
make = initMake;
model = initModel;
color = initColor;
year = initYear;
price = initPrice;
fourWD = initFourWD;
}
public String toString() {
String name = "SUV";
String main = new String();
if (fourWD) {
main = ("4WD " + color + " " + make + " " + model + " " + name + " (" + year + ") costs $" + price);
}
else {
main = (color + " " + make + " " + model + " " + name + " (" + year + ") costs $" + price);
}
return main;
}
}
class truckClass {
String make;
String model;
String color;
int year;
double price;
boolean fourWD;
boolean isheavyDuty;
String carries;
public truckClass(String initMake, String initModel, int initYear, double initPrice, boolean initisheavyDuty, String initCarries){
make = initMake;
model = initModel;
year = initYear;
price = initPrice;
isheavyDuty = initisheavyDuty;
carries = initCarries;
}
public String toString() {
String name = "Truck";
String main = (make + " " + model + " " + name + " (" + year + ") carries" + carries + " costs $" + price);
return main;
}
class vanClass {
String make;
String model;
int year;
double price;
boolean isCovered;
String carries;
public vanClass(String initMake, String initModel, int initYear, double initPrice, boolean initisCovered, String initCarries){
make = initMake;
model = initModel;
year = initYear;
price = initPrice;
isCovered = initisCovered;
carries = initCarries;
}
public String toString() {
String name;
String main;
if (isCovered()){
name = "covered Van";
String main = (make + " " + model + " " + name + " (" + year + ") carries" + carries + " costs $" + price);
}
else {
name = "Van";
String main = (make + " " + model + " " + name + " (" + year + ") carries" + carries + " costs $" + price);
}
return main;
}
}
public class autoPark {
public static void main(String args[]) {
sedan sedan1; // declaring cars object by name sedan1
sedan1 = new sedan("Ford" , "Model-1" , "white" , 2015, 20000); // initialising sedan1 using sedan constructor
System.out.println(sedan1); // printing sedan1 for invoking toString() method
SUV suv; // declaring cars object by name suv
suv = new SUV("Ford" , "Model-1" , "white" , 2015, 20000, true); // initialising suv using SUV constructor
System.out.println(suv); // printing suv for invoking toString() method
truckClass truck; //declaring cars object by name truck
truck = new truckClass("Ford" , "Model-1" , 2015, 20000, true, "2"); // initialising truck using truck constructor
System.out.println(truck); // printing truck for invoking toString() method
vanClass van;
van = new vanClass("Ford" , "Model-1" , 2015, 20000, true, "2";
System.out.println(van);
}
}
I came across 4 issues
missing } just before starting vanClass
missing ) after van = new vanClass("Ford" , "Model-1" , 2015, 20000, true, "2");
extra pair of parenthesis after isCovered which is a member data instead of method
Declaring main as String twice inside the toString method of SUV class
import java.util.*;
class sedan {
String make;
String model;
String color;
int year;
double price;
boolean fourWD;
boolean isheavyDuty;
String carries;
public sedan(String initMake, String initModel, String initColor, int initYear, double initPrice) {
make = initMake;
model = initModel;
color = initColor;
year = initYear;
price = initPrice;
}
#Override
public String toString() {
String name = "Sedan";
String main = (color + " " + make + " " + model + " " + name + " (" + year + ") costs $" + price);
return main;
}
}
class SUV {
String make;
String model;
String color;
int year;
double price;
boolean fourWD;
String carries;
public SUV(String initMake, String initModel, String initColor, int initYear, double initPrice, boolean initFourWD){
make = initMake;
model = initModel;
color = initColor;
year = initYear;
price = initPrice;
fourWD = initFourWD;
}
public String toString() {
String name = "SUV";
String main = new String();
if (fourWD) {
main = ("4WD " + color + " " + make + " " + model + " " + name + " (" + year + ") costs $" + price);
}
else {
main = (color + " " + make + " " + model + " " + name + " (" + year + ") costs $" + price);
}
return main;
}
}
class truckClass {
String make;
String model;
String color;
int year;
double price;
boolean fourWD;
boolean isheavyDuty;
String carries;
public truckClass(String initMake, String initModel, int initYear, double initPrice, boolean initisheavyDuty, String initCarries){
make = initMake;
model = initModel;
year = initYear;
price = initPrice;
isheavyDuty = initisheavyDuty;
carries = initCarries;
}
public String toString() {
String name = "Truck";
String main = (make + " " + model + " " + name + " (" + year + ") carries" + carries + " costs $" + price);
return main;
}
}
class vanClass {
String make;
String model;
int year;
double price;
boolean isCovered;
String carries;
public vanClass(String initMake, String initModel, int initYear, double initPrice, boolean initisCovered, String initCarries){
make = initMake;
model = initModel;
year = initYear;
price = initPrice;
isCovered = initisCovered;
carries = initCarries;
}
public String toString() {
String name;
String main;
if (isCovered){
name = "covered Van";
main = (make + " " + model + " " + name + " (" + year + ") carries" + carries + " costs $" + price);
}
else {
name = "Van";
main = (make + " " + model + " " + name + " (" + year + ") carries" + carries + " costs $" + price);
}
return main;
}
}
public class autoPark {
public static void main(String args[]) {
sedan sedan1; // declaring cars object by name sedan1
sedan1 = new sedan("Ford" , "Model-1" , "white" , 2015, 20000); // initialising sedan1 using sedan constructor
System.out.println(sedan1); // printing sedan1 for invoking toString() method
SUV suv; // declaring cars object by name suv
suv = new SUV("Ford" , "Model-1" , "white" , 2015, 20000, true); // initialising suv using SUV constructor
System.out.println(suv); // printing suv for invoking toString() method
truckClass truck; // declaring cars object by name truck
truck = new truckClass("Ford" , "Model-1" , 2015, 20000, true, "2"); // initialising truck using truck constructor
System.out.println(truck); // printing truck for invoking toString() method
vanClass van;
van = new vanClass("Ford" , "Model-1" , 2015, 20000, true, "2");
System.out.println(van);
}
}
You need to consider using inheritance as mentioned by others.
I fixed and refactored your class using inheritance:
abstract class Vehicle{
protected String maker;
protected String model;
protected int year;
protected double price;
public Vehicle(String maker, String model, int year, double price) {
this.maker=maker;
this.model=model;
this.year=year;
this.price=price;
}
abstract String getType();
#Override
public String toString() {
return maker + " " + model + " " + getType() + " (" + year + ") costs $" + price;
}
}
abstract class HeavyVehicle extends Vehicle{
protected String carries;
public HeavyVehicle(String maker, String model, int year, double price, String carries) {
super(maker, model, year, price);
this.carries=carries;
}
}
class SUV extends HeavyVehicle{
String color;
boolean fourWD;
public SUV(String maker, String model, String initColor, int year, double price,
boolean initFourWD) {
super(maker,model,year,price,"1");
color = initColor;
fourWD = initFourWD;
}
public String toString() {
StringBuilder sb = new StringBuilder();
if (fourWD) {
sb.append("4WD ");
}
sb.append(color + " " + super.toString());
return sb.toString();
}
#Override
String getType() {
return "SUV";
}
}
class Truck extends HeavyVehicle{
public Truck(String maker, String model, int year, double price,String carries) {
super(maker,model,year,price,carries);
}
public String toString() {
return maker + " " + model + " " + getType() + " (" + year + ") carries" + carries + " costs $" + price;
}
#Override
String getType() {
return "Truck";
}
}
class Van extends HeavyVehicle{
boolean isCovered;
public Van(String maker, String model, int year, double price, boolean isCovered, String carries){
super(maker,model,year,price,carries);
this.isCovered = isCovered;
}
public String toString() {
String name = isCovered ? "covered Van" : getType();
return maker + " " + model + " " + name + " (" + year + ") carries" + carries + " costs $" + price;
}
#Override
String getType() {
return "Van";
}
}
class Sedan extends Vehicle{
String color;
public Sedan(String maker, String model, String color, int year, double price) {
super(maker,model,year,price);
this.color = color;
}
#Override
public String toString() {
return color + " " + super.toString();
}
#Override
String getType() {
return "Sedan";
}
}
public class Main {
public static void main(String args[]) {
Sedan sedan1; // declaring cars object by name sedan1
sedan1 = new Sedan("Ford", "Model-1", "white", 2015, 20000); // initialising sedan1 using sedan constructor
System.out.println(sedan1); // printing sedan1 for invoking toString() method
SUV suv; // declaring cars object by name suv
suv = new SUV("Ford", "Model-1", "white", 2015, 20000, true); // initialising suv using SUV constructor
System.out.println(suv); // printing suv for invoking toString() method
Truck truck; // declaring cars object by name truck
truck = new Truck("Ford", "Model-1", 2015, 20000, "2"); // initialising truck using truck constructor
System.out.println(truck); // printing truck for invoking toString() method
Van van;
van = new Van("Ford", "Model-1", 2015, 20000, true, "2");
System.out.println(van);
}
}
Was missing a } and ). Silly mistake
I have this class in scala:
class AuthResponse( val ip: String,
val authorized: Boolean,
val sid: String,
val uid: String,
val ratio: Double,
val skipRecording: Boolean,
val rejectReason: String,
val userTrackingState: String,
val pid: Int = conf.getString(s"WebRecorder.Environments.${conf.getString("WebRecorder.Current.Environment")}.Pid").toInt) {
// If we write val before input vars it constract the same values
//Override toString method
override def toString: String = {
"ip: " + ip + "\n" +
"authorized: " + authorized + "\n" +
"sid: " + sid + "\n" +
"uid: " + uid + "\n" +
"ratio: " + ratio + "\n" +
"skipRecording: " + skipRecording + "\n" +
"rejectReason: " + rejectReason + "\n" +
"pid: " + pid + "\n" +
"userTrackingState: " + userTrackingState
}
}
object AuthResponse {
def apply(ip: String, authorized: Boolean, sid: String, uid: String, ratio: Double, skipRecording: Boolean, rejectReason: String, userTrackingState: String): AuthResponse =
new AuthResponse(ip, authorized, sid, uid, ratio, skipRecording, rejectReason, userTrackingState)
def apply(responseAsJson: String): AuthResponse = {
new Gson().fromJson(responseAsJson, classOf[AuthResponse])
}
}
I am trying to make it java code as follow:
public class AuthResponse {
String ip;
Boolean authorized;
String sid;
String uid;
Double ratio;
Boolean skipRecording;
String rejectReason;
String userTrackingState;
int pid = Integer.parseInt(Configuration.prop.getProperty(""));
#Override
public String toString(){
return
("ip: " + ip + "\n" +
"authorized: " + authorized + "\n" +
"sid: " + sid + "\n" +
"uid: " + uid + "\n" +
"ratio: " + ratio + "\n" +
"skipRecording: " + skipRecording + "\n" +
"rejectReason: " + rejectReason + "\n" +
"pid: " + pid + "\n" +
"userTrackingState: " + userTrackingState + "\n");
}
class AuthResponse(){
public AuthResponse apply(String ip,boolean authorized, String sid,String uid, double ratio,boolean skipRecording, String rejectReason, String userTrackingState){
return new AuthResponse(ip,authorized,sid,uid,ratio,skipRecording,rejectReason,userTrackingState);
}
public com.pipe.pipeapp.AuthResponse apply(String responseAsJson){
return new
}
}
}
I am trying to see how i can implment another class inside my class with the same name as for scala we can use object and class and it is completely different classes (since it is not class but object) but in Java we cannot do that, how can I implement the same class including object class in java?
Scala object might be compiled into different things depending on what's inside. In your case object AuthResponse is actually compiled in something that is similar to Java static methods on the class AuthResponse itself. So it would be something like this:
public class AuthResponse {
public final String ip;
public final Boolean authorized;
public final String sid;
public final String uid;
public final Double ratio;
public final Boolean skipRecording;
public final String rejectReason;
public final String userTrackingState;
public final int pid;
public AuthResponse(String ip, Boolean authorized, String sid, String uid, Double ratio, Boolean skipRecording, String rejectReason, String userTrackingState, int pid) {
this.ip = ip;
this.authorized = authorized;
this.sid = sid;
this.uid = uid;
this.ratio = ratio;
this.skipRecording = skipRecording;
this.rejectReason = rejectReason;
this.userTrackingState = userTrackingState;
this.pid = pid;
}
public AuthResponse(String ip, Boolean authorized, String sid, String uid, Double ratio, Boolean skipRecording, String rejectReason, String userTrackingState) {
this(ip, authorized, sid, uid, ratio, skipRecording, rejectReason, userTrackingState, Integer.parseInt(Configuration.prop.getProperty("")));
}
#Override
public String toString() {
return
("ip: " + ip + "\n" +
"authorized: " + authorized + "\n" +
"sid: " + sid + "\n" +
"uid: " + uid + "\n" +
"ratio: " + ratio + "\n" +
"skipRecording: " + skipRecording + "\n" +
"rejectReason: " + rejectReason + "\n" +
"pid: " + pid + "\n" +
"userTrackingState: " + userTrackingState + "\n");
}
public static AuthResponse apply(String ip, boolean authorized, String sid, String uid, double ratio,
boolean skipRecording, String rejectReason, String userTrackingState) {
return new AuthResponse(ip, authorized, sid, uid, ratio, skipRecording, rejectReason, userTrackingState);
}
public static AuthResponse apply(String responseAsJson) {
return new Gson().fromJson(responseAsJson, AuthResponse.class);
}
}
Although going to Java I would rename apply methods to something more meaningful such as create. Also you may introduce getters for fields instead of making them just public but I didn't bother to make the code shorter.
I let you documentation that can help in that case Nested Classes Java. Here explain when use nested classes When to Use.
I try to change the values of coupe but the output doesn't change. In NetBeans, I saved these two programs under the same project and package. I did not include it here because it may have made the code too long, but I also wrote accessor methods which work fine, so I am confused as to why the mutator methods don't work.
Class code:
package auto;
public class Auto
{
private String model;
private int milesDriven;
private double gallonsOfGas;
public Auto(String startModel,
int startMilesDriven,
double startGallonsOfGas)
{
model = startModel;
setMilesDriven(startMilesDriven);
setGallonsOfGas(startGallonsOfGas);
}
public void setModel(String newModel)
{
model = newModel;
}
public void setMilesDriven(int newMilesDriven)
{
if (newMilesDriven >= 0)
milesDriven = newMilesDriven;
else
{
System.err.println("Miles driven cannot be negative.");
System.err.println("Value not changed.");
}
}
public void setGallonsOfGas(double newGallonsOfGas)
{
if (newGallonsOfGas >= 0.0)
gallonsOfGas = newGallonsOfGas;
else
{
System.err.println("Gallons of gas cannot be negative.");
System.err.println("Value not changed.");
}
}
}
Client class code:
package auto;
import java.text.DecimalFormat;
public class AutoClient
{
public static void main(String [] args)
{
DecimalFormat milesPattern = new DecimalFormat("#,###");
Auto coupe = new Auto("Corvette", 300000, 0.0);
String coupeModel = coupe.getModel();
int coupeMiles = coupe.getMilesDriven();
double coupeGallons = coupe.getGallonsOfGas();
System.out.println("coupe:"
+ "\nmodel: " + coupeModel
+ "\nmiles: " + milesPattern.format(coupeMiles)
+ "\ngallons: " + coupeGallons);
coupe.setModel("Viper");
coupe.setMilesDriven(10000);
coupe.setGallonsOfGas(50.0);
System.out.println("coupe:"
+ "\nmodel: " + coupeModel
+ "\nmiles: " + milesPattern.format(coupeMiles)
+ "\ngallons: " + coupeGallons);
}
}
Given your current code, after you changed the values
coupe.setModel("Viper");
coupe.setMilesDriven(10000);
coupe.setGallonsOfGas(50.0);
You need to get them again
coupeModel = coupe.getModel();
coupeMiles = coupe.getMilesDriven();
coupeGallons = coupe.getGallonsOfGas();
Before you can call
System.out.println("coupe:"
+ "\nmodel: " + coupeModel
+ "\nmiles: " + milesPattern.format(coupeMiles)
+ "\ngallons: " + coupeGallons);
I suggest you update Auto and add a toString()
#Override
public String toString() {
return "coupe:"
+ "\nmodel: " + coupeModel
+ "\nmiles: " + milesPattern.format(coupeMiles)
+ "\ngallons: " + coupeGallons;
}
Then you can replace (in both places)
System.out.println("coupe:"
+ "\nmodel: " + coupeModel
+ "\nmiles: " + milesPattern.format(coupeMiles)
+ "\ngallons: " + coupeGallons);
With
System.out.println(coupe); // <-- Java will call toString() for you
I have JSON string that needs to be converted in Java object using Google Gson library.
I am stuck in converting due to forward slash in the following JSON string.
{
"status":"200",
"results":{
"resultitems":[
{
"uri":"/document/id/e20a8dad50d91a839c50ab5f323f3df3",
"path":"Data/xyz/abcdata",
"metadata":{
"data/category/item":"yahoo/post",
"ast_id":"67677"
}
}
]
}
Indeed, for Data/category/item, I am getting a null value. How can I correctly parse it?
Just a starting note: the JSON you put in request is not a valid JSON, but can be easily fixed adding a brace (I used fixed JSON in my answer).
I suggest you to parse your JSON this way. Declare the following classes.
public class Container {
public int status;
public Results results;
#Override
public String toString() {
return "Container [status=" + status + ", results=" + results + "]";
}
}
public class Results {
public List<ResultItem> resultitems;
#Override
public String toString() {
return "Results [resultitems=" + resultitems + "]";
}
}
public class ResultItem {
String uri;
String path;
HashMap metadata;
#Override
public String toString() {
return "ResultItem [uri=" + uri + ", path=" + path + ", metadata="
+ metadata + "]";
}
}
and then call this code:
public class Q19684865 {
public static void main(String[] args) {
String json = " { "
+ " \"status\":\"200\", "
+ " \"results\":{ "
+ " \"resultitems\":[ "
+ " { "
+ " \"uri\":\"/document/id/e20a8dad50d91a839c50ab5f323f3df3\", "
+ " \"path\":\"Data/xyz/abcdata\", "
+ " \"metadata\":{ "
+ " \"data/category/item\":\"yahoo/post\", "
+ " \"ast_id\":\"67677\" "
+ " } "
+ " } "
+ " ] "
+ " } "
+ " } ";
Container c = new Gson().fromJson(json, Container.class);
System.out.println("this is the parsed json: " +c);
System.out.println("this is the property 'data/category/item': "+c.results.resultitems.get(0).metadata.get("data/category/item"));
}
and this is the result:
this is the parsed json: Container [status=200, results=Results [resultitems=[ResultItem [uri=/document/id/e20a8dad50d91a839c50ab5f323f3df3, path=Data/xyz/abcdata, metadata={data/category/item=yahoo/post, ast_id=67677}]]]]
this is the property 'data/category/item': yahoo/post
Explanation: normally you need just POJOs if you do not have particular needs, where POJO field name corresponds to the label of the JSON value. But 'data/category/item' cannot be a valid Java identifier. So I chose to parse to a Map.
A second way could be to replace in JSON string your "data/category/item" with a valid Java identifier, "data_category_item" for example or, if you can change JSON origin, do the same at the source.