I'm new at JSON and i am currently struggling with a problem parsing JSON data in a list of objects.
The data that i am trying to parse is generated by the facebook graph api, and looks like this :
{
"100001621071794": {
"id": "100001621071794",
"name": "TEST1",
"username": "test1",
"link": "http://www.facebook.com/test1",
"gender": "male",
"picture": "http://profile.ak.fbcdn.net/test1.jpg"
},
"534237692": {
"id": "534237692",
"name": "TEST2",
"username": "test2",
"link": "http://www.facebook.com/test2",
"gender": "female",
"picture": "http://profile.ak.fbcdn.net/test2.jpg"
}
}
I am using the following code to parse :
Dim MyFacebookUsers As List(Of FacebookUser) = MyTwitterSerializer.Deserialize(Of List(Of FacebookUser))(FBData)
The class FacebookUser looks like this :
Public Class FacebookUser
Public id As String
Public name As String
Public username As String
Public link As String
Public gender As String
Public picture As String
End Class
I know that this is not an array, because it is missing '[' and ']'. But when i replace the '{' and '}' with '[' and ']' i'm getting an error because of an invlaid matrix.
Can someone please point me in the right direction?
You're right, that's not a JSON Array, it's an Object containing FacebookUser Objects where the id value is also the element key.
In .NET the Dictionary class is the JSON Object equivalent, so presumably something like
Dim MyFacebookUsers As List(Of FacebookUser) = MyTwitterSerializer.Deserialize(Of Dictionary(Of FacebookUser))(FBData)
is what you need.
As you discovered, you can't turn it into a Array (list) by just changing the braces. However, if you actually had an Array, it would look like this:
[
{"id": "100001621071794",
"name": "TEST1",
"username": "test1",
"link": "http://www.facebook.com/test1",
"gender": "male",
"picture": "http://profile.ak.fbcdn.net/test1.jpg"
},
{"id": "534237692",
"name": "TEST2",
"username": "test2",
"link": "http://www.facebook.com/test2",
"gender": "female",
"picture": "http://profile.ak.fbcdn.net/test2.jpg"
}
]
and your code would have worked fine.
Related
So I'm looking at something similar to this:
POST https://xxxx.io/testAPI
{
"test": "string",
"data": {
"name": "",
"description": "string",
}
}
Adding general headers is fine:
NCLient3.QueryString.Add("test", "Test string")
But for data -> name and data -> description, how would I do it in this regard as it's an array?
Well, First, this is not a valid JSON.
{
"test": "string",
"data": {
"name": "",
"description": "string"
}
}
You can get their values using Linq.
Dim json As String = "{'test': 'string','data': {'name': '','description': 'string'}}"
Dim jsn = Newtonsoft.Json.Linq.JObject.Parse(json)
Dim finalvalue As String = jsn.GetValue("data").Item("description").ToString()
and you'll get the value => string
I would like to get the value from the response based on a condition and store it to a variable.
In the below JSON, I would like to store the value when the name matches to something I prefer. Is there a way to achieve this using Karate API?
{
"results": [
{
"name": "Sample1",
"email": "sample1#text.com",
"id": "U-123"
},
{
"name": "Sample2",
"email": "sample2#text.com",
"id": "U-456"
},
{
"name": "Sample3",
"email": "sample3#text.com",
"id": "U-789"
}
]
}
So after reading the comment, my interpretation is to "find" the id where name is Sample2. Easy, just use a filter() operation, refer the docs: https://github.com/karatelabs/karate#jsonpath-filters
Instead of using a filter, I'm using the JS Array find() method as a very concise example below:
* def response =
"""
{ "results": [
{ "name": "Sample1", "email": "sample1#text.com", "id": "U-123" },
{ "name": "Sample2", "email": "sample2#text.com", "id": "U-456" },
{ "name": "Sample3", "email": "sample3#text.com", "id": "U-789" }
]
}
"""
* def id = response.results.find(x => x.name == 'Sample2').id
* match id == 'U-456'
Take some time to understand how it works. Talk to someone who knows JS if needed.
I am struggling from the morning with a query. I have the following JSON :
{
"id": "87ee51c7-3f15-4772-a2fb-bee379e1054d",
"description": "What color do you like?",
"option1": "Yellow",
"option2": "Blue",
"option3": "Green",
"option4": "Red",
"option5": "Pink",
"votes": [
{
"id": "26bf4e30-c75a-4267-8850-4f04101fdd35",
"answerOption": "Pink",
"user": {
"id": "f836bd80-53d8-4623-8198-ca375abfdbbc",
"authId": "auth0|5ff8fe4bee9af4febf00762c3f1e",
"firstName": "Test",
"lastName": "Name",
"phone": "07545166181",
"email": "user#yahoo.com",
"buildingStreet": "test",
"buildingNumber": "15",
"buildingName": "8",
"buildingEntrance": "A",
"town": "town",
"country": "country",
"other": ""
},
"date": "2021-01-30"
},
{
"id": "0047474f-ecf1-424b-960a-a512e6bb14f5",
"answerOption": "Blue",
"user": {
"id": "7da77dff-a22a-47ac-b995-41fa90866016",
"authId": "auth0|60055f048ec4a3006ee36d64",
"firstName": "John",
"lastName": "Doe",
"phone": "0755888999",
"email": "user2#yahoo.com",
"buildingStreet": "street",
"buildingNumber": "15",
"buildingName": "8",
"buildingEntrance": "A",
"town": "town",
"country": "country",
"other": ""
},
"date": "2021-01-30"
}
],
"status": "active",
"endDate": "2021-02-05"
}
So I have a Poll, with an id, description and 5 options to vote. The Poll has a list of votes, so i have multiple votes.
Each vote contains an answer, date and user.
Is there a query to build a list of users knowing the question id ?
The idea is to build this list of user who already vote so i restrict them to vote twice for the same Poll.
I am using Hibernate as ORM, Spring Boot for back and React for front.
List findAllUsers....where poll id is...
Is there a way to get there with a statement ? Lately I am using Hibernate and I am very rusty with handmade queries.
Thank you in advance
Assuming the data structure looks nearly like this:
public class User {
#Id private Long id;
// getters & setters
}
public class Vote {
#Id private Long id;
#ManyToOne private Poll poll;
#ManyToOne private User user;
// getters & setters
}
public class Poll {
#OneToMany List<Vote> votes;
// getters & setters
}
Using repositories, IMHO the cleanest place where to specify would be the VoteRepository. For that, the repository should look like this (using query generation with method names, see Query Methods in Spring Data JPA Reference Guide):
public interface VoteRepository extends JpaRepository<Vote> {
List<Vote> findByPoll(Poll poll);
}
Then, to get all the users related to a poll, e. g. in a controller, mapping from votes to users should be done:
#Autowired
VoteRepository voteRepository;
public List<User> getUsersRelatedToPoll(Poll poll) {
List<Vote> votes = voteRepository.findByPoll(poll);
return votes.stream().map(Vote::getUser).collect(Collectors.toList());
}
Another way, IMHO not the cleanest way (^1), could be a #Query method (see Using #Query in Spring Data JPA Reference Guide). This method would look like this:
public interface FooRepository extends JpaRepository<Foo> {
#Query("SELECT v.user FROM VOTE as v WHERE v.poll = :poll")
List<User> findUsersByPoll(#Param("poll") Poll poll);
}
^1: I think, e. g. in the UserRepository should not know about or use Poll or Vote ...
I have payload POST call:
{
"tenantName":"loki",
"owner":
{
"country": "india",
"firstName": "raj",
"lastName": "kumar",
"locale": "in",
"organization": "softwareag",
"phone": "9789155778",
"title": "mr",
"userName": "raraj#softwareag.com",
"email": "raraj#softwareag.com",
"password":"V2VsY29tZUAxMjM0"
},
"products": [
"cumulocity",
"b2b"
]
}
In that payload, the tenant name is unique, How to pass different values for each post call?
You can use __RandomString to randomize name, for example 5 lower case letters:
${__RandomString(5,abcdefghijklmnopqrstuvwxyz,)}
RandomString function returns a random String of length using characters in chars to use
Or load name values from CSV Data set config
You can use __groovy() function in order to call RandomStringUtils.randomAlphabetic() method like:
${__groovy(org.apache.commons.lang3.RandomStringUtils.randomAlphabetic(4),)}
replace 4 with the number of your choice to make the random string shorter or longer
The function can be inlined directly into your request body
{
"tenantName": "${__groovy(org.apache.commons.lang3.RandomStringUtils.randomAlphabetic(4),)}",
"owner": {
"country": "india",
"firstName": "raj",
"lastName": "kumar",
"locale": "in",
"organization": "softwareag",
"phone": "9789155778",
"title": "mr",
"userName": "raraj#softwareag.com",
"email": "raraj#softwareag.com",
"password": "V2VsY29tZUAxMjM0"
},
"products": [
"cumulocity",
"b2b"
]
}
More information: Apache Groovy - Why and How You Should Use It
I have managed to store a Json file to my database using c#, I created a Model for every value for a Json like this :
[{
"id": "1",
"val1": "Json2 Test2",
"val2": "Json2 Test2",
"val3": "Json2 Test2",
"val4": "Test2"
},
{
same
}]
But I have another Json like this :
"count": 2,
"value": [
{
"id": "1",
"val1": "aaa",
"val2": "aaaa",
"collection": {
"id": "2",
"val1": "bbbb",
"val2": "bbb"
},
"collection2": {
"id": "3",
"val1": "cccc",
"val2": "cccc"
},
{
same
}]
My model in cs in basically the same and for the collection I use
[JsonProperty(PropertyName = "collection1")]
public IList<string> Collection1 { get; set; }
But I don't see how I can upload all this Json in my DataBase. Should I create another table for collection1 and collection2 ?
I use this also :
string data = streamReader.ReadToEnd();
List<Json1> json1= JsonConvert.DeserializeObject<List<Json1>>(data);
Thank you for the help