Last active
December 29, 2019 17:58
-
-
Save SamWolfs/3ed17f79aa4f4675342fa76a86ed8609 to your computer and use it in GitHub Desktop.
Parse partial JSON object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.google.gson.Gson; | |
public class App { | |
public static void main(String[] args) { | |
Gson gson = new Gson(); | |
String json = "{\"type\":\"bankaccount\",\"payload\":{\"bankAccountNo\":\"BE123\"}}"; | |
// String json = "{\"type\":\"newuser\",\"payload\":{\"firstName\":\"Sam\",\"lastName\":\"Wolfs\"}}"; | |
Message msg = gson.fromJson(json, Message.class); | |
switch (msg.getType()) { | |
case "bankaccount": | |
ChangeBankAccount changeBA = gson.fromJson(msg.getPayload(), ChangeBankAccount.class); | |
System.out.println(changeBA.getBankAccountNo()); | |
break; | |
case "newuser": | |
NewUser newUser = gson.fromJson(msg.getPayload(), NewUser.class); | |
System.out.println(newUser.getFirstName() + " " + newUser.getLastName()); | |
break; | |
default: | |
break; | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ChangeBankAccount { | |
private String bankAccountNo; | |
public String getBankAccountNo() { | |
return bankAccountNo; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.google.gson.JsonObject; | |
public class Message { | |
private String type; | |
private JsonObject payload; | |
public String getType() { | |
return type; | |
} | |
public JsonObject getPayload() { | |
return payload; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class NewUser { | |
private String firstName; | |
private String lastName; | |
public String getFirstName() { | |
return firstName; | |
} | |
public String getLastName() { | |
return lastName; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment