改造获取带有空字段的对象

时间:2018-06-21 14:28:14

标签: java c# android asp.net-core retrofit2

我使用Retrofit 2.4,尝试从Asp.Net Core 2.0 WebApi服务获取数据。

这里是Java类:

public class Category {
private int CategoryID;
private String Name;
private String Image;

public Category(){
    Name="";
    Image="";
}

public Category(int categoryID, String name, String image) {
    Name = name;
    Image = image;
    CategoryID=categoryID;
}

public  int getCategoryID() {return CategoryID;}

public String getName() {
    return Name;
}

public void setName(String name) {
    Name = name;
}

public String getImage() {
    return Image;
}

public void setImage(String image) {
    Image = image;
}

}

此处改装代码:

public class Common {
public static User CURRENT_USER;
public static String SERVER_NAME="http://ip_address:5000";
public static IApiService ApiService;
public Common()
{
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(SERVER_NAME)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    ApiService = retrofit.create(IApiService.class);
}

}

public interface IApiService
 { 
  @GET("api/Categories")
  Call<List<Category>> GetCategoryColl();
 }

然后我通过Asp.Net Core 2.0 WebApi编写服务器端。

我有一个控制器:

   [Produces("application/json")]
[Route("api/Categories")]
public class CategoriesController : Controller
{
    private readonly MovieAppServerContext _context;

    public CategoriesController(MovieAppServerContext context)
    {
        _context = context;
    }

    // GET: api/Categories
    [HttpGet]
    public IEnumerable<Category> GetCategory()
    {
        return _context.Category;
    }

    // GET: api/Categories/5
    [HttpGet("{id}")]
    public async Task<IActionResult> GetCategory([FromRoute] int id)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var category = await _context.Category.SingleOrDefaultAsync(m => m.CategoryID == id);

        if (category == null)
        {
            return NotFound();
        }

        return Ok(category);
    }

    // PUT: api/Categories/5
    [HttpPut("{id}")]
    public async Task<IActionResult> PutCategory([FromRoute] int id, [FromBody] Category category)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        if (id != category.CategoryID)
        {
            return BadRequest();
        }

        _context.Entry(category).State = EntityState.Modified;

        try
        {
            await _context.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!CategoryExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return NoContent();
    }

    // POST: api/Categories
    [HttpPost]
    public async Task<IActionResult> PostCategory([FromBody] Category category)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        _context.Category.Add(category);
        //await _context.SaveChangesAsync();
        _context.SaveChanges();

        return Ok(category);
    }

    // DELETE: api/Categories/5
    [HttpDelete("{id}")]
    public async Task<IActionResult> DeleteCategory([FromRoute] int id)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var category = await _context.Category.SingleOrDefaultAsync(m => m.CategoryID == id);
        if (category == null)
        {
            return NotFound();
        }

        _context.Category.Remove(category);
        //   await _context.SaveChangesAsync();
        _context.SaveChanges();

        return Ok("Removed!");
    }

    private bool CategoryExists(int id)
    {
        return _context.Category.Any(e => e.CategoryID == id);
    }
}

这里是类别的服务器端类:

  public class Category
{
    [Key]
    public int CategoryID { get; set; }

    public String Name { get; set; }
    public String Image { get; set; }

    public Category()
    {
    }

    public Category(String name, String image)
    {
        Name = name;
        Image = image;
    }
}

因此,我通过Swagger检查服务器代码,并且运行良好:我从类别列表中获取了所有数据。 但是,当我尝试通过Retrofit从Android代码获取数据时-我收到了带有空对象的集合:所有字段均为null或为空(我认为这是默认值)。

所以,这里的代码:

public class Home extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

   List<Category> _categoryList =new ArrayList<>();
   @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_home);
  //some code 
     Common.ApiService.GetCategoryColl().enqueue(new Callback<List<Category>>() {
        @Override
        public void onResponse(Call<List<Category>> call, Response<List<Category>> response) {
            Log.i("GetCategories",response.message());
            _categoryList=response.body();
              // !!!! HERE. _category list contains objects but all of them 
                //  are empty!



        }

        @Override
        public void onFailure(Call<List<Category>> call, Throwable t) {
            Log.e("GetCategories",t.getMessage());
        }
    });
    }
 }

所以,我不知道为什么会这样?如何解决? 谢谢!

2 个答案:

答案 0 :(得分:1)

您尚未在Java @SerializedName("json-key-name")类的字段中添加Category

@SerializedName("categoryId")
private int CategoryID;

@SerializedName("name")
private String Name;

@SerializedName("image")
private String Image;

现在GSON可以将JSON响应正确地映射到POJO。

答案 1 :(得分:1)

默认情况下,Gson期望字段名称与Json相同,如果要更改此行为,则有两个选择:

1。使用FieldNamingPolicy(对于您的情况为UPPER_CAMEL_CASE),下面是如何进行翻新的示例:

 Gson gson = new GsonBuilder()
            .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
            .create();

 Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(SERVER_NAME)
        .addConverterFactory(GsonConverterFactory.create())
        .build();

2。在Java字段上使用SerializedName批注。