I have this class.
public class SDS
{
public Guid A { get; set; }
public Guid B { get; set; }
public String C { get; set; }
}
I return the json like this
public HttpResponseMessage Val()
{
SDS svr = new SDS();
svr.A = ...
svr.B = ...
svr.C = ...
return Request.CreateResponse(HttpStatusCode.OK, json_serializer.Serialize(svr), "application/json");
}
In the client side I use jquery like this
var obj = jQuery.parseJSON(jqXHR.responseText);
The problem is that the json that gets returned is like this and I am unable to iterate ofer the values or access the elements via index:
{"A":"3a9779fe-9c92-4208-b34d-5113e0548d50","B":"206575a5-8a90-4a13-89ec-910e5a9a35a1","C":"Meta"}
To solve this issue I had to do this and this works:
obj = jQuery.parseJSON('{"List":[' + obj + ']}');
My question is is there any way to use an attribute on the class so that it returns a json that I can use?
[SomeAttribute name="List"]
public class SDS
{
public Guid A { get; set; }
public Guid B { get; set; }
public String C { get; set; }
}
...
...
...
Update2:
This question is still open as none of the provided answers were able to produce a fix.
You can return a JsonResult by calling Json() in your action method.
public ActionResult Get(int id)
{
var item = ...
return Json(item);
}
Did you try to use the JsonResult from System.Web.Mvc.JsonResult ?
public JsonResult Val() {}
Hope this Helps.
The JSON returned is correct, don't change anything in your controller
..but in your JS loop the object with a for in loop
for(var propertyName in obj){
...
}
propertyName gives you A, B and C
and...
var value = obj[propertyName]
gives you the value
Well, you're returning a single object, not a list, but you could do:
public HttpResponseMessage Val()
{
SDS svr = new SDS();
svr.A = ...
svr.B = ...
svr.C = ...
var list = new {List = new [] {svr}};
return Request.CreateResponse(HttpStatusCode.OK, json_serializer.Serialize(svr), "application/json");
}
add ApiController and using System.Web.Http;
Related
When the below API method is called through the API
public IActionResult FirstStudent()
{
var collection = this.database.GetCollection<BsonDocument>("students");
var filter = Builders<BsonDocument>.Filter.Eq("RollNo", "1");
var document = collection.Find(filter).First();
var firstStudent= document.ToJson();
return Ok(firstStudent);
}
the response has Content-Type as text/plain.
I need the Content-Type as application/json.
Any suggestions?
the easiest thing to do would be to create a student model and simply return an ok result with the student model like this:
public class Student
{
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public int RollNo { get; set; }
public string Name { get; set; }
}
public IActionResult FirstStudent()
{
var collection = this.database.GetCollection<Student>("Student");
var filter = Builders<Student>.Filter.Where(s => s.RollNo == 1);
var document = collection.Find(filter).First();
return Ok(document);
}
I'm having a bit of an issue here. I am getting all my products from a mongodb collection with this function:
public async Task<string> getAllProducts()
{
List<string> all = new List<string>();
var document = await getCollection("produits").Find(new BsonDocument()).ToCursorAsync();
foreach (var doc in document.ToEnumerable())
{
var res = doc.ToJson();
all.Add(res);
}
return JsonConvert.SerializeObject(all);
}
and it returns a JSON that looks like this to my react front end.
{ "_id" : ObjectId("5e49bdf5f040e808847a17d7"),
"email" : "example#gmail.com",
"quantite" : 1,
"matricule" : 1}
problem is i cant parse this in my javascript because of this : ObjectId("5e49bdf5f040e808847a17d7")
Of course I could do some string magic before I parse it, but id rather it be corrected on the server side. So is there a way I can get rid of this problem and get a result like this?
{ "_id" : "5e49bdf5f040e808847a17d7",
"email" : "example#gmail.com",
"quantite" : 1,
"matricule" : 1}
give this a try. it will serialize string ids without objectid stuff.
public static async Task<string> getAllProducts()
{
var collection = db.GetCollection<object>("produits");
var all = new List<object>();
using (var cursor = await collection.FindAsync("{}"))
{
while (await cursor.MoveNextAsync())
{
foreach (var doc in cursor.Current.ToArray())
{
all.Add(doc);
}
}
}
return Newtonsoft.Json.JsonConvert.SerializeObject(all);
}
Fixed by creating a class for the mongodb object.
public class Product
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public int matricule { get; set; }
public int quantite { get; set; }
public string email { get; set; }
public float prix { get; set; }
public string image { get; set; }
}
get them and deserialize with BsonSerializer :
public async Task<List<Product>> getAllProducts(){
var collection = await getCollection("produits").Find(new BsonDocument()).ToListAsync();
List<Product> all = new List<Product>();
foreach(var doc in collection){
all.Add(BsonSerializer.Deserialize<Product>(doc));
}
return all;
}
return them on request :
[HttpGet]
public async Task<string> ShowProductsAsync()
{
MongodbModel model = new MongodbModel();
var products = await model.getAllProducts();
Console.WriteLine(products);
return JsonConvert.SerializeObject(products);
}
string GetAllProduits(){
var collection = database.GetCollection<BsonDocument>("produits");
var project = Builders<BsonDocument>.Projection.Exclude("_id");
var filter = Builders<BsonDocument>.Filter.Empty;
var rlt=collection.Find(filter).Project(project);
return rlt.ToList().ToJson();
}
So I have 2 objects,AlbumDto and AlbumMediaDto.
public class AlbumDto
{
public int AlbumId { get; set; }
public string Title { get; set; }
public DateTimeOffset? AlbumDate { get; set; }
public AlbumMediasDto Media { get; set; }// list of media
}
And I have a method from the repo that would return a list of albums (where each has the properties mentioned above which includes a list of media)
var albumsForChild = await GetTenantRepository<IAlbumRepository>().GetAlbumsForChild(childId);
So I'm not sure how to map them to these Dtos using the AutoMapper ( I know that I can always use a nested foreach and fill everything accordingly but thought of learning how to do this the right way).
Any help appreciated!
Can you work with JSon deserialization? If yes, below can be your solution.
Business logic:
public IEnumerable<AlbumDto> GetAllAlbums()
{
var allAlbums = _theApiWrapper.ExecuteGet<IEnumerable<AlbumDto>>("theApiRoute");
return allAlbums;
}
Repository:
public T ExecuteGet<T>(string endpoint)
{
var uri = $"https://apiurl.company.com/api/v1/{endpoint}";
using (HttpClient client = new HttpClient())
{
var x = client.GetAsync(uri);
var result = x.Result.Content.ReadAsStringAsync().Result;
return JsonConvert.DeserializeObject<T>(
result,
new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }
);
}
}
I'm trying to return an object to an ajax request with an api 2 controller in an MVC 5 app. my controller looks like this:
public class RFQsController : ApiController
{
private ApplicationDBContext db = new ApplicationDBContext();
[HttpGet]
public Models.RFQChecklist.RFQ GetRFQByQuote(string number)
{
var quote = db.QuoteSet.FirstOrDefault(q => q.Number == number);
if(quote != null)
{
return quote.RFQ?.FirstOrDefault();
}
else
{
return null;
}
}
}
RFQ looks like this:
public class RFQ
{
public int ID { get; set; }
public int QuoteID { get; set; }
//other values
[XmlIgnore, JsonIgnore]
public virtual Quote.Quote Quote { get; set; }
public virtual ICollection<RFQ_Signoff> Signoffs { get; set; }
}
It's important to ignore Quote because Quote has a reference to its contained RFQs, so that would be a circular reference. So when serializing an RFQ for consumption, I'm trying to ignore Quote, because Quote has to reference RFQ. The problem is that XmlIgnore isn't... ignoring. I've also tried ScriptIgnore, and the combination of DataContract/DataMember. No matter what I do, the MVC 5 serializer seems to try (and fail) to serialize the Quote object again.
I'm quite certain it is because of this value, because if I remove JsonIgnore then it doesn't work when I try to retrieve as Json, but if I include it it works.
If you want to limit your return data you need to use linq select instead of [XmlIgnore, JsonIgnore] attribute.
you can try to use an anonymous object to contain your expect return fields.
return quote.RFQ?.Select(x => new {
ID = x.ID,
QuoteID = x.QuoteID,
Signoffs = x.Signoffs }).FirstOrDefault();
instead of
return quote.RFQ?.FirstOrDefault();
Try to return IHttpActionResult
[HttpGet]
public IHttpActionResult GetRFQByQuote(string number)
{
var quote = db.QuoteSet.FirstOrDefault(q => q.Number == number);
if(quote != null)
{
var result = quote.RFQ?.Select(x => new {
ID = x.ID,
QuoteID = x.QuoteID,
Signoffs = x.Signoffs }).FirstOrDefault()
return Ok(result);
}
else
{
return null;
}
}
This is where I get my data.
$contacts = array();
while ($row = mysqli_fetch_array($stmt))
{
$contact = array("ID" => $row['ProduktID'],
"Name" => $row['ProduktNamn'],
"Number" => $row['ProduktPris']);
array_push($contacts, $contact);
}
echo json_encode(array('results' => $contacts), JSON_PRETTY_PRINT);
And now when I use it in my code in Xamarin I can write the entire thing out in the log but not when I try to write out a certain "Name" of a table for example. This is the code:
static public async Task<JObject> getOurMainInfo()
{
var httpClientRequest = new HttpClient ();
var result = await httpClientRequest.GetAsync ("http://localhost/getmystuff.php");
var resultString = await result.Content.ReadAsStringAsync ();
var jsonResult = JObject.Parse (resultString);
// var jsonResult = JsonConvert.DeserializeObject<Contact>(resultString); //Should I implement this somehow to my JObject? Contact is my public class.
System.Diagnostics.Debug.WriteLine (jsonResult["Name"]); //i get nothing in the log. if i remove ["Name"] i get the entire data in the log.
return jsonResult;
}
My public class (If i need this to connect and work with th edatbase somehow):
public class Contact
{
public string ID { get; set; }
public string Name { get; set; }
public string Number { get; set; }
}