JavaScriptDeserializer exception parsing JSON response - asp.net

I am parsing a JSON response from Citrix' web services. The response looks like this
[{\"webinarKey\":123456,\"subject\":\"Subject\",\"description\":\"Webinar Description. \",\"organizerKey\":123456,\"times\":[{\"startTime\":\"2012-05-08T16:00:00Z\",\"endTime\":\"2012-05-08T17:00:00Z\"}],\"timeZone\":\"America/New_York\"}]
I manually edited that string to remove identifying information, so if there is a missing quote or anything it is unrelated.
I followed the example from this answer on SO, but still am encountering an error.
Deserializing JSON result with Json & JavaScriptSerializer
public class Webinars {
public string webinarKey;
public string subject;
public string description;
public string organizerKey;
public WebinarTimes[] times;
public string timeZone;
}
public class WebinarTimes {
public string startTime;
public string endTime;
}
JavaScriptSerializer jss = new JavaScriptSerializer();
var foo = jss.Deserialize<Webinars>(JSON);
I receive the following error: Type 'Web.Site.Webinars' is not supported for deserialization of an array.

You have to use IList<Webinars> instead of Webinars
var foo = jss.Deserialize<IList<Webinars>>(JSON);

Related

org.springframework.data.solr.UncategorizedSolrException: Collection not found

I am using spring-data-solr to query indexed Solr data running on a Hadoop cluser. The name of my collection is party_name. Below is the code I used to configure the Cloud client:
#Configuration
#EnableSolrRepositories(basePackages = { "org.nccourts.repository" }, multicoreSupport = true)
public class SpringSolrConfig {
#Value("${spring.data.solr.zk-host}")
private String zkHost;
#Bean
public SolrClient solrClient() {
return new CloudSolrClient(zkHost);
}
#Bean
public SolrTemplate solrTemplate(CloudSolrClient solrClient) throws Exception {
solrClient.setDefaultCollection("party_name");
return new SolrTemplate(solrClient);
}
}
When I run my JUnit test, I am getting the following exception:
org.springframework.data.solr.UncategorizedSolrException: Collection not found: partyname; nested exception is org.apache.solr.common.SolrException: Collection not found: partyname
at org.springframework.data.solr.core.SolrTemplate.execute(SolrTemplate.java:215)
at org.springframework.data.solr.core.SolrTemplate.executeSolrQuery(SolrTemplate.java:1030)
Note the collection not found: partyname, but the collection name I entered is
party_name.
I am using Spring Boot version 1.5.2 with the following dependency:
compile('org.springframework.boot:spring-boot-starter-data-solr')
Any help or pointers are appreciated.
Your suggestion gave me the idea. My model looked like this:
public class PartyName {
#Field("case_status")
private String caseStatus;
private String county;
#Field("court_type")
private String courtType;
private String id;
#Field("in_regards_to")
private String inRegardsTo;
#Field("biz_name")
private String bizName; // business name after parsing name
#Field("first_name")
private String firstName; // person 1st name after parsing name
#Field("last_name")
private String lastName; // person last name after parsing name
#Field("middle_name")
private String middleName; // person middle name after parsing name
private String name; // original name before parsing
private String prefix; // person prefix after parsing name
private String suffix; // person name suffix after parsing name
#Field("party_num")
private Integer partyNumber;
#Field("party_role")
private String partyRole;
#Field("party_status")
private String partyStatus;
#Field("row_of_origin")
private String rowOrigin;
#Field("seq_num")
private Integer seqNumber;
private Integer year;
... getter/setter omitted.
}
When you suggested for me to post my entity code, I realized I needed to add the following annotation:
#SolrDocument(solrCoreName = "party_name")
public class PartyName {
..
After I did that, the JUnit worked fine. Thanks.

Spring MVC JSON deserialization with malformed JSON ( Jackson )

On a REST api i receive a Json that gets mapped to a Java Object:
#RequestMapping(value = "/example", method = RequestMethod.POST)
public #ResponseBody
ReturnObject doReturn(#RequestBody ProblemObject requestBody)
The object is simple:
public class ProblemObject implements Serializable {
private String field1;
private String field2;
public ProblemObject(String field2) {
this.field2 = field2;
}
public ProblemObject(String field1, String field2) {
this.field1 = field1;
this.field2 = field2;
}
}
The problem is Jackson tries to deserialize even malformed JSON, with not so good results, for example it accepts:
"field1": "test",
"field2": "test"
}
notice no opening brace. This causes the object to get mapped with field1 having a value of "field2" and field2 being null.
It also accepts no comma with even worse results.
For now the only alternative i can think of is implementing a custom deserialiser but that is not optimal imho.
Is there a way to make Jackson more strict?
I would try being more explicit in your #RequestMapping annotation and telling the API what it should be consuming:
#RequestMapping(value = "/example", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
This is apparently a bug in the TokenBuffer in Jackson. An issue has been opened and a Jackson dev has confirmed the bug.
It is due to the single String constructor. Removing the constructor if possible is a temporary workaround.

Return JSON for ResponseEntity<String>

I have a method in my controller that should returns a String in JSON. It returns JSON for non primitive types:
#RequestMapping(value = "so", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<String> so() {
return new ResponseEntity<String>("This is a String", HttpStatus.OK);
}
The curl response is:
This is a String
The root of the problem is that Spring (via ResponseEntity, RestController, and/or ResponseBody) will use the contents of the string as the raw response value, rather than treating the string as JSON value to be encoded. This is true even when the controller method uses produces = MediaType.APPLICATION_JSON_VALUE, as in the question here.
It's essentially like the difference between the following:
// yields: This is a String
System.out.println("This is a String");
// yields: "This is a String"
System.out.println("\"This is a String\"");
The first output cannot be parsed as JSON, but the second output can.
Something like '"'+myString+'"' is probably not a good idea however, as that won't handle proper escaping of double-quotes within the string and will not produce valid JSON for any such string.
One way to handle this would be to embed your string inside an object or list, so that you're not passing a raw string to Spring. However, that changes the format of your output, and really there's no good reason not to be able to return a properly-encoded JSON string if that's what you want to do. If that's what you want, the best way to handle it is via a JSON formatter such as Json or Google Gson. Here's how it might look with Gson:
import com.google.gson.Gson;
#RestController
public class MyController
private static final Gson gson = new Gson();
#RequestMapping(value = "so", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity<String> so() {
return ResponseEntity.ok(gson.toJson("This is a String"));
}
}
#RequestMapping(value = "so", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody String so() {
return "This is a String";
}
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;
public ResponseEntity<?> ApiCall(#PathVariable(name = "id") long id) throws JSONException {
JSONObject resp = new JSONObject();
resp.put("status", 0);
resp.put("id", id);
return new ResponseEntity<String>(resp.toString(), HttpStatus.CREATED);
}
An alternative solution is to use a wrapper for the String, for instances this:
public class StringResponse {
private String response;
public StringResponse(String response) {
this.response = response;
}
public String getResponse() {
return response;
}
}
Then return this in your controller's methods:
ResponseEntity<StringResponse>

ASMX Web Service (ASP.net 2.0) - Serializable Dictionary not serialized

All,
I have an instance of ProjectBudget class returned from a web method.
Ex:
[WebMethod()]
public ProjectBudget LoadBudget(int id)
{
ProjectBudget budget = BudgetManager.LoadBudget(id);
return budget;
}
The ProjectBudget class contains the following defintion:
public class ProjectBudget
{
public int Id = -1;
public long VersionNumber = -1;
public string QuoteNumber = "";
public string CurrencyCode = "";
public ProjectInfo Project;
public ClientInfo Client;
public readonly List<InventoryItem> Inventory = new List<InventoryItem>();
public readonly List<Staff> Staff = new List<Staff>();
public readonly List<CodeType> Departments = new List<CodeType>();
public readonly SerializableDictionary<string, string> Tasks = new SerializableDictionary<string, string>();
public ProjectBudget()
{
}
}
All public fields you see are serialized just fine with the exception of Tasks field, which is completely ignored by XML serializer. Since we all know by now that Dictionaries cannot be handled by XML serializer, I use a serializable dictionary (which is just a dictionary that implements IXmlSerializable) here but XML serializer decides to ignore it completely, i.e. the XML output does not contain any tasks and the generated proxy class doesn't have this field.
I need to figure out how to tell the XML serializer not to omit this field.
Btw, what is interesting is that a web method that returns SerializableDictionary works fine!
A very similar question as yours appears to have been asked already: Link.
Use DataContractSerializer or try explicitly implementing your getter (and setter), as per this link.

Deserializing a PHP json encoded (json_encode) string with ASP.NET webservices

I am really struggling deserializing a PHP json encoded string in ASP.NET.
I am using nusoap and CakePHP 1.3 on the PHP side and mvc.net 4.0 on the web service side and everything was working well. However, I couldn’t figure out how to pass a complex array as one parameter of the webservice, so I had the idea of serializing it as json and passing a simple string. So far so good...
But I cannot for the life of me de-serialize the json_encoded string in ASP.NET [well, I’ve been trying for the last two hours at least ;)]
Here is what I have so far:
The PHP sends an array of products (product id as a GUID - sent as a string then converted on the web service side) and the number of products:
$args['products'] = json_encode($booking['Booking']['prs_products']);
This is received ok by the webservice as the following json string (products):
[{"BookingProducts":{"id":"2884f556-67ed-4eb8-98ca-a99dc27a2665","quantity":2}},{"BookingProducts":{"id":"f57854ba-0a9b-400b-bea0-bafdcb179b01","quantity":2}},{"BookingProducts":{"id":"7ff81128-c33c-4e6c-a33c-3ca40ccfb5d0","quantity":2}}]
I then try and populate a BookingProducts List<>. The BookingProducts class is as follows:
public class BookingProducts
{
public String id { get; set; }
public int quantity { get; set; }
public BookingProducts()
{
}
public BookingProducts(string id, int quantity)
{
this.id = id;
this.quantity = quantity;
}
}
I have tried both the [System.Web.Script.Serialization][2] and Newtonsoft.Json libraries as follows, but without success:
List<BookingProducts> productsList = new List<BookingProducts>();
try
{
productsList = JsonConvert.DeserializeObject<List<BookingProducts>>((products));
}
catch (Newtonsoft.Json.JsonSerializationException)
{
productsList = new JavaScriptSerializer().Deserialize<List<BookingProducts>>(products);
}
In both cases I get a list of empty products (or a serialization exception).
Hopefully someone has done this before, or can spot an obvious mistake!
What you really have here is a list of objects containing BookingProducts object. In order to deserialize it, you need to have something like this for your entity:
public class BookingProductsWrapper
{
public class BookingProductsInner
{
public string id { get; set; }
public int quantity { get; set; }
}
public BookingProductsInner BookingProducts { get; set; }
}
Now you can deserialize it using JavaScriptSerializer (for example):
System.Web.Script.Serialization.JavaScriptSerializer jsSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<BookingProductsWrapper> productsList = jsSerializer.Deserialize<List<BookingProductsWrapper>>(products);
That will do the trick.

Resources