Gson in Android Studio - java

I try to save data to object user by gson but have an error:
java.lang.RuntimeException: com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Unterminated string at line 1 column 911330 path $.assignedUser....................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................
at com.loopj.andro
User class is:
public class User {
#SerializedName("id")
int id;
#SerializedName("frontName")
String name;
#SerializedName("email")
String email;
#SerializedName("phoneNumber")
String phoneNumber;
#SerializedName("pesel")
String pesel;
#SerializedName("readableAdress")
String adress;
#SerializedName("avatar")
String avatar;
#SerializedName("city")
String city;
}
and code where I use gson:
User user = new User();
String response = new String(responseBody, "UTF-8");
Gson gson = new Gson();
user = gson.fromJson(response, User.class);
Problem is in the structure of the string response?

It seems that your JSON string is malformed. You can try this tool to validate it before parsing it with GSON.
https://jsonformatter.curiousconcept.com/

User Class:
public class UserData {
private int id;
private String name;
private String email;
private String phoneNumber;
private String pesel;
private String address;
private String avatar;
private String city;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getPesel() {
return pesel;
}
public void setPesel(String pesel) {
this.pesel = pesel;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
Now parse it like this:
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
Gson gson = new Gson();
response = gson.fromJson(br, User.class);

Related

Error while deleting data from dynamoDB table

I am trying to delete the data from my DynamoDB table based on the Id(HashKey).
Association.java
#DynamoDBTable(tableName = "Association")
public class Association {
private String id;
private String name;
private String adminName;
private String email;
private String url;
private String contactNumber;
private String password;
public Association() { }
public Association(String name, String adminName, String email, String url,
String contactNumber, String password) {
this.name = name;
this.adminName = adminName;
this.email = email;
this.url = url;
this.contactNumber = contactNumber;
this.password = password;
}
public Association(String id, String name, String adminName, String email, String url,
String contactNumber, String password) {
this.id = id;
this.name = name;
this.adminName = adminName;
this.email = email;
this.url = url;
this.contactNumber = contactNumber;
this.password = password;
}
#DynamoDBHashKey(attributeName = "Id")
#DynamoDBAutoGeneratedKey
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#DynamoDBAttribute(attributeName="Name")
public String getName() { return name; }
public void setName(String name) { this.name = name; }
#DynamoDBAttribute(attributeName="AdminName")
public String getAdminName() { return adminName; }
public void setAdminName(String adminName) { this.adminName = adminName; }
#DynamoDBAttribute(attributeName="Email")
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
#DynamoDBAttribute(attributeName="Url")
public String getUrl() { return url; }
public void setUrl(String url) { this.url = url; }
#DynamoDBAttribute(attributeName="ContactNumber")
public String getContactNumber() { return contactNumber; }
public void setContactNumber(String contactNumber) { this.contactNumber = contactNumber; }
#DynamoDBAttribute(attributeName="Password")
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
}
AssociationRepository.java:-
private AmazonDynamoDBClient getDynamoDBClient(){
AmazonDynamoDBClient client = new AmazonDynamoDBClient();
client.setRegion(Region.getRegion(REGION));
client.setEndpoint(EndPoint);
return client;
}
private void deleteAssociation(String id) {
try {
DynamoDBConfig dynamoDBConfig = new DynamoDBConfig();
DynamoDBMapper mapper = new DynamoDBMapper(dynamoDBConfig.getDBClient());
Association associationToDelete = new Association();
associationToDelete.setId(id);
// Delete the item.
mapper.delete(associationToDelete);
} catch (Exception exception) {
System.out.println(exception);
throw exception;
}
}
I am getting the below error:-
com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMappingException: No method annotated with interface com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBRangeKey for class class Association
I have searched the AWS docs for this but could not find any solution that fixes this.Does anyone of you ever faced this issue?
The issue is the same I mentioned on your other post, in DynamoDB you can’t work an item using attributes which are not the primary key (Partition Key only in your scenario).
Moreover, to delete an item it is mandatory to do it by its primary key, so in your case the attribute Name.
Try to do same operation by setting the name, the error is not very descriptive so maybe there is another underlying issue. However, if you don’t meet above requirement it will never work.

Error while retrieving data by Id(hashKey) of a dynamoDb table

I am trying to fetch the data from my DynamoDB table based on the Id(HashKey).
Association.java
#DynamoDBTable(tableName = "Association")
public class Association {
private String id;
private String name;
private String adminName;
private String email;
private String url;
private String contactNumber;
private String password;
public Association() { }
public Association(String name, String adminName, String email, String url,
String contactNumber, String password) {
this.name = name;
this.adminName = adminName;
this.email = email;
this.url = url;
this.contactNumber = contactNumber;
this.password = password;
}
public Association(String id, String name, String adminName, String email, String url,
String contactNumber, String password) {
this.id = id;
this.name = name;
this.adminName = adminName;
this.email = email;
this.url = url;
this.contactNumber = contactNumber;
this.password = password;
}
#DynamoDBHashKey(attributeName = "Id")
#DynamoDBAutoGeneratedKey
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#DynamoDBAttribute(attributeName="Name")
public String getName() { return name; }
public void setName(String name) { this.name = name; }
#DynamoDBAttribute(attributeName="AdminName")
public String getAdminName() { return adminName; }
public void setAdminName(String adminName) { this.adminName = adminName; }
#DynamoDBAttribute(attributeName="Email")
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
#DynamoDBAttribute(attributeName="Url")
public String getUrl() { return url; }
public void setUrl(String url) { this.url = url; }
#DynamoDBAttribute(attributeName="ContactNumber")
public String getContactNumber() { return contactNumber; }
public void setContactNumber(String contactNumber) { this.contactNumber = contactNumber; }
#DynamoDBAttribute(attributeName="Password")
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; }
}
AssociationRepository.java:-
private AmazonDynamoDBClient getDynamoDBClient(){
AmazonDynamoDBClient client = new AmazonDynamoDBClient();
client.setRegion(Region.getRegion(REGION));
client.setEndpoint(EndPoint);
return client;
}
public Association fetchById(String id) {
DynamoDBConfig dynamoDBConfig = new DynamoDBConfig();
DynamoDBMapper mapper = new DynamoDBMapper(getDBClient());
Association association = new Association();
association.setId(id);
Association scanResult = null;
try {
scanResult = mapper.load(association);
}
catch (Exception exception){
throw exception;
}
return scanResult;
}
Invoking fetchById("123"). Where "123" is an existing Id of the table It throws the below error to me:-
{
"errorMessage": "The provided key element does not match the schema (Service: AmazonDynamoDBv2; Status Code: 400; Error Code: ValidationException; Request ID: IT6U9BJ0RAJUDPMLGGR67C542VVV4KQNSO5AEMVJF66Q9ASUAAJG)",
"errorType": "com.amazonaws.AmazonServiceException",
"stackTrace": [
"com.amazonaws.http.AmazonHttpClient.handleErrorResponse(AmazonHttpClient.java:1305)",
"com.amazonaws.http.AmazonHttpClient.executeOneRequest(AmazonHttpClient.java:852)",
DYNAMODB TABLE DETAILS:-
I have searched the AWS docs for this but could not find any solution that fixes this.Does anyone of you ever faced this issue?
If you realize, you defined Name as your partition key. However on code, you are trying to load an item by the attribute Id.
That's not possible as DynamoDB only allows you to load an item by its primary key, which in your case is only the partition key (the attribute Name).
So you have to modify either the table to set Id as partition key, or create a secondary global index to accomplish that:
https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GSI.html

Parse JSON in java (Eclipse)

I have the following JSON text (REST API URL SOURCE). How can I parse it to get ID, name, phone,city etc:
{"ID":1,"name":"aaa","phone":["345345345","1244","743"],"city":"asdasd"}
{"ID":2,"name":"bbb","phone":["234234","235","124"]}
{"ID":3,"name":"ccc","phone":["4234","6236","123"],"city":"jhjk"}
thanks.
EDIT:
I Run this code:
String var1 = output;
JSONObject obj;
try {
obj = new JSONObject(var1);
String a = obj.getString("name");
String b = obj.getString("phone");
String c = obj.getString("city");
System.out.println("name:" + a);
System.out.println("phone:" + b);
System.out.println("city:" + c);
and I got "phone" as a string .
someone can add the code to parse the phone line?
You can use Gson to parse the JSON. Simply create a class for this and Gson will do the parsing for you.
class MyClass{
#SerializedName("ID")
String ID;
#SerializedName("name")
String name;
#SerializedName("phone")
List<String> phone;
#SerializedName("city")
String city;
public MyClass(String ID, String name, List<String> phone, String city) {
this.ID = ID;
this.name = name;
this.phone = phone;
this.city = city;
}
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getPhone() {
return phone;
}
public void setPhone(List<String> phone) {
this.phone = phone;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
then in your main class or activity:
MyClass myclass= new Gson().fromJSON(jsonString,MyClass.class);
System.out.println(myclass.getID());
Make use of org.json libarary.
Afterwards, create an instance of JSONObject and JSONArray to parse the JSON String

Looping through the entire firebase data

I would like to find the data of all the users and sum of their scores on particular questions and find the highest rank
Now I can walk through the data users data but not through the questions node.
How do read all the data
This is how I have created my POJO :
private String id;
private String name;
private String contact;
private String email;
private String password;
private int score;
private String dob;
private String profession;
private String random;
private String status;
private String fbId;
private UserPuzzleDetails userPuzzleDetails;
public User() {
}
public User(String id, String name, String contact, String email, String password, int score,
String dob, String profession, String random, String status, String facebookid, UserPuzzleDetails userPuzzleDetails1) {
this.id = id;
this.name = name;
this.contact = contact;
this.email = email;
this.password = password;
this.score = score;
this.dob = dob;
this.profession = profession;
this.random = random;
this.status = status;
this.fbId = facebookid;
this.userPuzzleDetails = userPuzzleDetails1;
}
public User(String id, String name, String contact, String email, String password, int score,
String dob, String profession, String random, String status, String facebookid) {
this.id = id;
this.name = name;
this.contact = contact;
this.email = email;
this.password = password;
this.score = score;
this.dob = dob;
this.profession = profession;
this.random = random;
this.status = status;
this.fbId = facebookid;
}
public User(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public String getPassword() {
return password;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public String getContact() {
return contact;
}
public String getDob() {
return dob;
}
public String getProfession() {
return profession;
}
public String getRandom() {
return random;
}
public UserPuzzleDetails getUserPuzzleDetails() {
return userPuzzleDetails;
}
public void setUserPuzzleDetails(UserPuzzleDetails questions) {
this.userPuzzleDetails = questions;
}
public String getStatus() {
return status;
}
public String getFbId() {
return fbId;
}
public void setFbId(String fbId) {
this.fbId = fbId;
}
Now I have used this function to retrieve the data but it is not logging.
How should I go by this data iterate through it.
private void getAllRank() {
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("users");
final Query query = databaseReference.orderByChild("score").limitToLast(10);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
userlist = new ArrayList<>();
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
User score = postSnapshot.getValue(User.class);
userlist.add(new User(score.getId(), score.getName(), score.getContact(), score.getEmail(),
score.getPassword(), score.getScore(), score.getProfession(), score.getDob(), score.getRandom(), score.getStatus(), score.getFbId(),score.getUserPuzzleDetails()));
Log.e(TAG, "onDataChange: "+userlist );
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}

Spring data Mongo DB retrieving data : #Document VO returns null

I am trying to retrieve data from mongodb via spring framework.
At first I made return type Map<String, Object>, but I decided to change to User value object.
Below is the class for User VO
#Document(collection = "user")
public class User {
#Id
#Field(value="id")
private String id;
#Field(value="name")
private String name;
#Field(value="password")
private String password;
#Field(value="professional")
private String professional;
#Field(value="email")
private String email;
#Field(value="gravatar")
private String gravatar;
#PersistenceConstructor
public User(String id, String name, String password, String professional, String email, String gravatar) {
super();
this.id = id;
this.name = name;
this.password = password;
this.professional = professional;
this.email = email;
this.gravatar = gravatar;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getProfessional() {
return professional;
}
public void setProfessional(String professional) {
this.professional = professional;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGravatar() {
return gravatar;
}
public void setGravatar(String gravatar) {
this.gravatar = gravatar;
}
};
and Here is #repository to retrieve data
#Repository
public class MongoMemberDao implements CommonDao<String, Map<String, Object>, Exception> {
#Autowired
MongoTemplate template;
final String COLLECTION_NAME = "user";
#SuppressWarnings("unchecked")
#Override
public Map<String, Object> read(String key) throws Exception {
Query findQuery = new Query();
findQuery.addCriteria(Criteria.where("id").is(key));
return template.findOne(findQuery, Map.class, COLLECTION_NAME);
}
public User readByDocument(String id) throws Exception {
Query findOneQuery = new Query();
findOneQuery.addCriteria(Criteria.where("id").is(id));
return template.findOne(findOneQuery, User.class, COLLECTION_NAME);
}
};
read method returns fine, but readByDocument does not(returns null not User instance). I read official document. But I do not get any clue of it.
FYI, The parameter Query looks same for both.
Query: { "id" : "system"}, Fields: null, Sort: null
I want to know why readByDocument returns null
Thanks.
---- Edit
Follow is my Database Config
#Configuration
public class MongoConfig extends AbstractMongoConfiguration {
private final String MONGO_URL = "127.0.0.1";
private final Integer MONGO_PORT = 27017;
#Override
protected String getDatabaseName() {
return "tfarm";
}
#Override
// #Bean
public Mongo mongo() throws Exception {
return new MongoClient(MONGO_URL, MONGO_PORT);
}
}
And I added this to WebApplictaionInitializer implement.
For current solution
I found follow on official site
A field annotated with #Id (org.springframework.data.annotation.Id)
will be mapped to the _id field.
A field without an annotation but named id will be mapped to the _id
field.
The default field name for identifiers is _id and can be customized
via the #Field annotation.
So I changed my VO like...
#Document(collection = "user")
public class User {
#Id
private ObjectId _id;
#Field(value="id")
private String id;
#Field(value="name")
private String name;
#Field(value="password")
private String password;
#Field(value="professional")
private String professional;
#Field(value="email")
private String email;
#Field(value="gravatar")
private String gravatar;
#PersistenceConstructor
public User(String id, String name, String password, String professional, String email, String gravatar) {
super();
this.id = id;
this.name = name;
this.password = password;
this.professional = professional;
this.email = email;
this.gravatar = gravatar;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public ObjectId get_id() {
return _id;
}
public void set_id(ObjectId _id) {
this._id = _id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getProfessional() {
return professional;
}
public void setProfessional(String professional) {
this.professional = professional;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGravatar() {
return gravatar;
}
public void setGravatar(String gravatar) {
this.gravatar = gravatar;
}
};
Added ObjectId. In alternative, just removing #Id annotation works fine too. However
#Id
#Field(value="id")
String id;
will not work. Thanks for help.

Categories