• Post Reply Bookmark Topic Watch Topic
  • New Topic

Java Generics with JSON  RSS feed

 
Robert Johnston
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all, I am starting to get into Java for things like Android and such, I have a long tenure in C# and the Microsoft world and have hopefully a simple question.

One of the things that I find great about C# is it's capability to work with generics.  I have looked into using generics with Java, which is pretty powerful. 

The one thing that I am not seeing or simply missing is the JSON to Data Type translation, for example, in C#: r.Content.ReadAsAsync<IEnumerable<MyDataType>>().Result

Is there something like above for Java?
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16060
88
Android IntelliJ IDE Java Scala Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is not (yet) a standard API for working with JSON in Java, but there are several libraries; my preference is Jackson.
 
Campbell Ritchie
Marshal
Posts: 56593
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There probably is, but please first explain what that C# code does.

I shall move you to the “General” forum because that looks like a difficult question.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
While in C# you can get the generic type at runtime, you can't do the same in Java because of type erasure. The usual workaround is to use Class literals. For instance, using Jackson:
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And since Class literals don't allow generics to nest more than 1 deep, Jackson has TypeReference:

Other frameworks may have similar constructs, but there's unfortunately no one-size-fits-all solution for that...
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!